在if中使用时,为什么使用LINQ更改属性

SAT*_*SAT 3 c# linq where

当我使用时someList.Where(t => t.isTrue = true)没有任何反应.但是,当我使用下面给出的代码时,

 if(someList.Where(t => t.isTrue = true).Count() > 0) 
    return;
Run Code Online (Sandbox Code Playgroud)

列表中的所有项都设置为true.为什么会这样?

编辑:我不是要分配或比较任何东西.我很好奇为什么会这样if.

Tit*_*mir 12

发生这种情况是因为您使用了=相等比较(==)的赋值().

此外,它只在您使用时才会发生,Count因为LINQ仅在必须获取值时才计算lambda表达式.

var q = someList.Where(t => t.isTrue = true); // Nothing will happen 
q.ToList() // would happen here 
if(q.Count() > 0 ) { .. } // Also here
Run Code Online (Sandbox Code Playgroud)

要比较而不是分配您应该使用的值:

var q = someList.Where(t => t.isTrue == true); 
var q = someList.Where(t => t.isTrue);  // Or simpler
Run Code Online (Sandbox Code Playgroud)

编译器允许这样做的原因是赋值是一个具有值的表达式.例如 :

int a = 10;
int b;
int c = (b = a) ; // (a=b) is of type int even though it also assigns a value, and b and c will have a value of 10
Run Code Online (Sandbox Code Playgroud)

在你的情况下,分配一个boolhas类型bool,它恰好是传递给lambda的有效返回值Where