2009-11-17 5 views
41

J'ai une simple expression lambda qui va quelque chose comme ceci:multiples Si des clauses dans Lambda expressions

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

Maintenant, si je veux ajouter une clause where à l'expression, par exemple, l.InternalName != String.Empty alors ce serait la expression être?

+1

Ceci est un peu hors-sujet, mais la La classe string a une méthode String.IsNullOrEmpty que vous pouvez utiliser plutôt que de la comparer à String.Empty –

Répondre

87

Peut être

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

ou

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

Lorsque vous êtes à la recherche à la mise en œuvre Where, vous pouvez le voir accepte un Func(T, bool); cela signifie:

  • T est votre type IEnumerable
  • bool signifie qu'il doit retourner une valeur booléenne

Alors, quand vous faites

.Where(l => l.InternalName != String.Empty) 
// ^     ^---------- boolean part 
//  |------------------------------ "T" part 
+6

+1 pour le commentaire booléen/T –

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

ou

x=> x.Lists.Include(l => l.Title).Where(l=>l.Title != String.Empty && l.Internal NAme != String.Empty) 
3

Peut-être

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

?

Vous pouvez probablement le mettre aussi dans la même clause where:

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

Vous pouvez l'inclure dans la même déclaration, où avec l'opérateur & & ...

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

Vous pouvez utiliser l'un des opérateurs de comparaison (pensez-y comme faire une déclaration if) comme ...

List<Int32> nums = new List<int>(); 

nums.Add(3); 
nums.Add(10); 
nums.Add(5); 

var results = nums.Where(x => x == 3 || x == 10); 

... ramènerait 3 et 10.

11

lambda que vous passez à Where peut inclure tout code normal C#, par exemple l'opérateur &&:

.Where(l => l.Title != string.Empty && l.InternalName != string.Empty) 
Questions connexes