[英]Multiple Where clauses in Lambda expressions
我有一個簡單的lambda表達式,如下所示:
x=> x.Lists.Include(l => l.Title).Where(l=>l.Title != String.Empty)
現在,如果我想在表達式中添加一個where子句,比如說l.InternalName != String.Empty
那么表達式是什么?
可
x => x.Lists.Include(l => l.Title)
.Where(l => l.Title != String.Empty && l.InternalName != String.Empty)
要么
x => x.Lists.Include(l => l.Title)
.Where(l => l.Title != String.Empty)
.Where(l => l.InternalName != String.Empty)
當您查看Where
實現時,您可以看到它接受Func(T, bool)
; 這意味着:
T
是你的IEnumerable類型 bool
意味着它需要返回一個布爾值 所以,當你這樣做的時候
.Where(l => l.InternalName != String.Empty)
// ^ ^---------- boolean part
// |------------------------------ "T" part
傳遞給Where
的lambda可以包含任何普通的C#代碼,例如&&
運算符:
.Where(l => l.Title != string.Empty && l.InternalName != string.Empty)
您可以使用&&運算符將其包含在相同的where語句中...
x=> x.Lists.Include(l => l.Title).Where(l=>l.Title != String.Empty
&& l.InternalName != String.Empty)
您可以使用任何比較運算符(將其視為執行if語句),例如...
List<Int32> nums = new List<int>();
nums.Add(3);
nums.Add(10);
nums.Add(5);
var results = nums.Where(x => x == 3 || x == 10);
...會帶回3和10。
也許
x=> x.Lists.Include(l => l.Title)
.Where(l => l.Title != string.Empty)
.Where(l => l.InternalName != string.Empty)
?
您也可以將它放在相同的where子句中:
x=> x.Lists.Include(l => l.Title)
.Where(l => l.Title != string.Empty && l.InternalName != string.Empty)
x=> x.Lists.Include(l => l.Title).Where(l=>l.Title != String.Empty).Where(l => l.Internal NAme != String.Empty)
要么
x=> x.Lists.Include(l => l.Title).Where(l=>l.Title != String.Empty && l.Internal NAme != String.Empty)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.