Multiple Where clauses in Lambda expressions

前端 未结 5 1370
臣服心动
臣服心动 2020-12-23 13:42

I have a simple lambda expression that goes something like this:

x=> x.Lists.Include(l => l.Title).Where(l=>l.Title != String.Empty)
相关标签:
5条回答
  • 2020-12-23 13:53
    x=> x.Lists.Include(l => l.Title).Where(l=>l.Title != String.Empty).Where(l => l.Internal NAme != String.Empty)
    

    or

    x=> x.Lists.Include(l => l.Title).Where(l=>l.Title != String.Empty && l.Internal NAme != String.Empty)
    
    0 讨论(0)
  • 2020-12-23 13:57

    Maybe

    x=> x.Lists.Include(l => l.Title)
        .Where(l => l.Title != string.Empty)
        .Where(l => l.InternalName != string.Empty)
    

    ?

    You can probably also put it in the same where clause:

    x=> x.Lists.Include(l => l.Title)
        .Where(l => l.Title != string.Empty && l.InternalName != string.Empty)
    
    0 讨论(0)
  • 2020-12-23 13:58

    You can include it in the same where statement with the && operator...

    x=> x.Lists.Include(l => l.Title).Where(l=>l.Title != String.Empty 
        && l.InternalName != String.Empty)
    

    You can use any of the comparison operators (think of it like doing an if statement) such as...

    List<Int32> nums = new List<int>();
    
    nums.Add(3);
    nums.Add(10);
    nums.Add(5);
    
    var results = nums.Where(x => x == 3 || x == 10);
    

    ...would bring back 3 and 10.

    0 讨论(0)
  • 2020-12-23 14:01

    The lambda you pass to Where can include any normal C# code, for example the && operator:

    .Where(l => l.Title != string.Empty && l.InternalName != string.Empty)
    
    0 讨论(0)
  • 2020-12-23 14:13

    Can be

    x => x.Lists.Include(l => l.Title)
         .Where(l => l.Title != String.Empty && l.InternalName != String.Empty)
    

    or

    x => x.Lists.Include(l => l.Title)
         .Where(l => l.Title != String.Empty)
         .Where(l => l.InternalName != String.Empty)
    

    When you are looking at Where implementation, you can see it accepts a Func(T, bool); that means:

    • T is your IEnumerable type
    • bool means it needs to return a boolean value

    So, when you do

    .Where(l => l.InternalName != String.Empty)
    //     ^                   ^---------- boolean part
    //     |------------------------------ "T" part
    
    0 讨论(0)
提交回复
热议问题