LINQ: adding where clause only when a value is not null

后端 未结 10 943
花落未央
花落未央 2020-12-15 17:38

I know a typical way is like this:

IQueryable query = from staff in dataContext.Staffs;
if(name1 != null)
{
     query = from staff in query where (staff.nam         


        
10条回答
  •  攒了一身酷
    2020-12-15 18:01

    The best way to do this is to create yourself an extension method that will take in a conditional statement and a where expression. If the condition is true then it will use the where expression else it will not use it. This can dramatically clean up your code, eliminating the need for if statements.

    public static class LinqExtensions
    {
        public static IQueryable WhereIf(this IQueryable query, bool condition, Expression> whereClause)
        {
            if (condition)
            {
                return query.Where(whereClause);
            }
            return query;
        }
    }
    

    Now you can write your code like this:

    IQueryable query = dataContext.Staffs.AsQueryable().WhereIf(name1 != null, x => x.Name == name1);
    

提交回复
热议问题