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

后端 未结 10 944
花落未央
花落未央 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:24

    I like use the Expression e.g.

        Expression> expresionFinal = c => c.Active == true;
    
        if (DateBirth.HasValue)
                    {
                        Expression> expresionDate = c => (EntityFunctions.TruncateTime(c.DateBirth) == DateBirth);
                        expresionFinal = PredicateBuilder.And(expresionFinal, expresionDate);
                    }
    
    IQueryable query = dataContext.Persons;
     query = query.Where(expresionFinal);
    

提交回复
热议问题