简体   繁体   中英

Multiple condition using Lambda Expression in C#

The following code works for me if I need to filter a generic query for a single parameter, like Status=1.

public static IQueryable<T> FilterBy<T>(this IQueryable<T> query)
        {
            var propertyName = "Status";
            var param_1 = "1";
            //var param_2 = 2;
            //var param_3 = "DE";

            var parameterExp = Expression.Parameter(typeof(T), "type");
            var propertyExp = Expression.Property(parameterExp, propertyName);

            var converter = TypeDescriptor.GetConverter(propertyExp.Type);
            var result = converter.ConvertFrom(param_1);
            var value = Expression.Constant(result);

            var equalBinaryExp = Expression.Equal(propertyExp, value);
            query = query.Where(Expression.Lambda<Func<T, bool>>(equalBinaryExp, parameterExp));

            return query;
        }

This is like filtering a list with a value.

var list = new List<Employee> {
                new Employee { Id = 1, Name = "Phil", Status=1, Country="DE" } ,
                new Employee { Id = 2, Name = "Kristina", Status=2, Country="DE" },
                new Employee { Id = 3, Name = "Mia", Status=1, Country="US" }
            };

            list = list.Where(x => (x.Status == 1)).ToList();

But how should I modify the method FilterBy, so that it will work for filtering multiple values? Like (Status=1 or Status=2) and Country="DE",

list = list.Where(x => (x.Status == 1 || x.Status == 2) && x.Country == "DE").ToList();

Thanks for your time.

The trick when writing lambdas by hand is to write them how you would in regular C#, and decompile them, perhaps using sharplab like this . If you look on the right, you can see that it is doing something like:

Expression.AndAlso(
    Expression.OrElse(
        Expression.Equal(idPropExp, Expression.Constant(1)),
        Expression.Equal(idPropExp, Expression.Constant(2))
    ),
    Expression.Equal(countryPropExp, Expression.Constant("DE"))
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM