Multiple Where clauses in Lambda expressions

C#.NetLambda

C# Problem Overview


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

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

Now, if I want to add one more where clause to the expression, say, l.InternalName != String.Empty then what would the expression be?

C# Solutions


Solution 1 - C#

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

Solution 2 - C#

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)

Solution 3 - C#

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.

Solution 4 - C#

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)

Solution 5 - C#

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)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionashwnacharyaView Question on Stackoverflow
Solution 1 - C#Rubens FariasView Answer on Stackoverflow
Solution 2 - C#AakashMView Answer on Stackoverflow
Solution 3 - C#user110714View Answer on Stackoverflow
Solution 4 - C#JoeyView Answer on Stackoverflow
Solution 5 - C#Winston SmithView Answer on Stackoverflow