使用|| LinQ的运营商

Tân*_*Tân 0 c# linq logical-operators

我有一个小例子来使用|| 运营商Where()但可能出现问题:

var list = new List<string>
{
   "One",
   "Two",
   "Three"
};

string s = "One";
var numbers = list.Where(x => x == s || !string.IsNullOrEmpty(x));

foreach(var number in numbers)
{
   Console.WriteLine(number);

   // output:
   // One
   // Two
   // Three
}

s = null;    
numbers = list.Where(x => x == s || !string.IsNullOrEmpty(x));

foreach(var number in numbers)
{
   Console.WriteLine(number);

   // output:
   // One
   // Two
   // Three
}
Run Code Online (Sandbox Code Playgroud)

在第一种情况下,为什么!string.IsNullOrEmpty(x)在我们x == s真的时候仍然检查?

我明白了:

if (A && B)
{
   // we need A and B are true
}

if (A || B)
{
   // we need A is true or B is true
   // if A is true, no ned to check B is true or not
}
Run Code Online (Sandbox Code Playgroud)

所以,我的问题是:我误解了什么?

Ian*_*Ian 7

你这样说是对的:

a || b
Run Code Online (Sandbox Code Playgroud)

不会评价b,如果atrue,但是:

WhereLINQ使用Lambda表达式检查Enumerable中的每个元素,而不管先前的结果如何.因此当你这样做时:

string s = "One";
var numbers = list.Where(x => x == s || !string.IsNullOrEmpty(x));
Run Code Online (Sandbox Code Playgroud)

只要Wherelambda表达式有效,它就会检查查询中的每个元素:

x == s || !string.IsNullOrEmpty(x)); //x = "One", x == s is true
x == s || !string.IsNullOrEmpty(x)); //x = "Two", !string.IsNullOrEmpty(x) is true
x == s || !string.IsNullOrEmpty(x)); //x = "Three", !string.IsNullOrEmpty(x) is true
Run Code Online (Sandbox Code Playgroud)

因此,您获得了所有元素.

TakeWhile如果您想在不再达到条件时立即停止获取查询结果,请考虑使用.