1 回答

TA貢獻1804條經(jīng)驗 獲得超7個贊
讓我們再看一些代碼。我們將測試這兩種情況:
首先,我們將使用兩個 if 語句來測試 &&
我們將使用兩個 Where 調(diào)用
所以:
var elements = new List<string>(new[] { "A", "B", "C" });
Console.WriteLine("C#'s &&");
elements.Where(x => {
if (x == "A")
{
Console.WriteLine("ConditionA is true");
if (1 == 1)
{
Console.WriteLine("ConditionB is true");
return true;
}
Console.WriteLine("ConditionB is false");
}
Console.WriteLine("ConditionA is false");
return false;
}).ToList();
Console.WriteLine();
Console.WriteLine("Double Linq.Where");
elements.Where(x => {
if (x == "A")
{
Console.WriteLine("ConditionA is true");
return true;
}
Console.WriteLine("ConditionA is false");
return false;
})
.Where(x => {
if (1 == 1)
{
Console.WriteLine("ConditionB is true");
return true;
}
Console.WriteLine("ConditionB is false");
return false;
}).ToList();
結果如下:
C#'s &&
ConditionA is true
ConditionB is true
ConditionA is false
ConditionA is false
Double Linq.Where
ConditionA is true
ConditionB is true
ConditionA is false
ConditionA is false
正如你所看到的,它是一樣的。未通過 ConditionA 的元素不會針對 ConditionB 進行測試。
你可以在這里試試這個:https ://dotnetfiddle.net/vals2r
- 1 回答
- 0 關注
- 122 瀏覽
添加回答
舉報