开发者

LINQ filter specific or all

开发者 https://www.devze.com 2023-01-23 08:18 出处:网络
I\'m passing a filter model to my service. The user can select any which is null or an empty string. How do i set up a one time .Where query that will know to ignore that filter?

I'm passing a filter model to my service. The user can select any which is null or an empty string. How do i set up a one time .Where query that will know to ignore that filter?

An example:

public class UserFilterModel
{
    public string State {get; set;};
    public string Age {get; set;};
}

The filter: (How do I make it better fit my needs?)

var result = context.Users.Where(u => u.State == filter.State && u.Age == filter.Age);

So if the user selects null or empty for State, this will currently return records with null or empty states when I actually want to ignore that filter.

Also, I'm usi开发者_开发问答ng asp.net mvc 2, incase I'm doing something completely wrong, please tell me. Using repository pattern.


Here's one way:

var result = context.Users.Where(
    u => (String.IsNullOrEmpty(filter.State) || u.State == filter.State) &&
         (String.IsNullOrEmpty(filter.Age) || u.Age == filter.Age)
);
0

精彩评论

暂无评论...
验证码 换一张
取 消