当我使用 someList.Where(t => t.isTrue = true)
时没有任何反应。但是当我使用下面给出的代码时,
if(someList.Where(t => t.isTrue = true).Count() > 0)
return;
列表中的所有项目都设置为 true。为什么会这样?
编辑:我不是要分配或比较任何东西。我很好奇为什么在与 if
一起使用时会发生这种情况。
最佳答案
发生这种情况是因为您使用了等式比较 (==
) 的赋值 (=
)。
此外,它仅在您使用 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
要比较而不是分配你应该使用的值:
var q = someList.Where(t => t.isTrue == true);
var q = someList.Where(t => t.isTrue); // Or simpler
编译器允许这样做的原因是赋值是一个有值的表达式。例如:
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
在您的情况下,bool
的赋值具有 bool
类型,这恰好是传递给 Where
的 lambda 的有效返回值>
关于c# - 为什么在 if 中使用 LINQ 会更改属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48882721/