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

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

    No, I am not strongly agree with you. here you just gave a simple logic

    if(name1 != null)
    // do your stuff
    

    but what will happen if you do something different with the name1 that have null value..!! Ok, now consider this situation. In this example you shows how to handle possible null values in source collections. An object collection such as an IEnumerable can contain elements whose value is null. If a source collection is null or contains an element whose value is null, and your query does not handle null values, a NullReferenceException will be thrown when you execute the query.

    Probably this could be a issue...

提交回复
热议问题