C# 为什么在if中使用LINQ会改变属性
当我使用C# 为什么在if中使用LINQ会改变属性,c#,linq,where,C#,Linq,Where,当我使用someList.Where(t=>t.isTrue=true)时,什么都不会发生。但当我使用下面给出的代码时 if(someList.Where(t => t.isTrue = true).Count() > 0) return; 列表中的所有项都设置为true。为什么会这样 编辑:我没有试图分配或比较任何内容。我很好奇为什么在与if一起使用时会发生这种情况,因为您使用了相等比较(=)的赋值(=) 此外,它仅在使用Count时发生,因为LINQ仅在必须获取值时
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
,它恰好是传递给的lambda的有效返回值,其中当您使用=
时,列表中的所有项都设置为true,然后使用Count()
计算表达式
由于isTrue是一个布尔值,这就足以计算为真的值
if(someList.Where(t => t.isTrue).Count() > 0)
return;
作为检查计数是否大于0的替代方法,您可以使用已经执行该操作的任何方法
if(someList.Where(t => t.isTrue).Any()) // Any returns true if there are any elements in the collection
return;
您可以通过将条件作为参数的Any重载来进一步简化此过程,从而跳过额外的Where
if(someList.Any(t => t.isTrue)) // This overload takes a function that returns a boolean like Where does and returns true if there is at least 1 element that matches the condition
return;
我认为您需要在c中查找基本运算符,因为=!===如果在比较中指定布尔值时编译器发出某种警告/s我的回答是否清楚了为什么会发生这种情况?@TitianCernicova Dragomir谢谢。我认为你是唯一理解这个问题的人:D@SAT一开始我觉得这是一种奇怪的行为,我已经看过好几次这个问题了,所以我知道困惑是从哪里来的:)他在哪里说他想数数东西?@MatJ,当他的代码在他的问题中使用.count()
?