Linq 中 where 子句中的单"="与"=="运算符有什么区别 - C#

  • 本文关键字:区别 子句 Linq where 运算符 c# linq
  • 更新时间 :
  • 英文 :


通过下面的示例代码,我试图了解 where 子句中的"="运算符与"=="之间的确切区别是什么?

我有属性为 IsActive 的项目列表。 当我这样做时:

GetAllItemsFromCache-- 只是返回List<Item>其中 2 个是IsActiveFalse的,其中 8 个是True

// this return 10 items whereas 2 of them were `IsActive` property was set to `false`in the initial list, but now IsActive seems true for all the items
bool someFlag = true;
var result = GetAllItemsFromCache().Where(i => i.IsActive = someFlag).ToList(); 
// this return nothing - In the list 2 of them were `IsActive` property was set to `false` 
bool someFlag = false;
var result = GetAllItemsFromCache().Where(i => i.IsActive = someFlag).ToList(); 
// using regular == operator just returns as expected based on the flag. No question here
bool someFlag = false;
var result = GetAllItemsFromCache().Where(i => i.IsActive == someFlag).ToList(); 

有人可以解释一下吗?(或者如果您共享链接以便我可以阅读详细信息(

在 C# 中,使用=运算符的赋值表达式返回分配的值,因此由于someFlag是布尔值,因此i.IsActive = someFlag返回的值是someFlag的值

这是语言规范:

简单赋值

表达式的结果是赋值 左操作数。结果与左操作数的类型相同,并且 始终分类为值。

更多信息在这里 : https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/expressions#assignment-operators

在 C# 中,当变量被初始化时,使用"="。

int a = 5;
int b = 6;

这里的"a"等于5,"b"等于6。

当您想决定某事时,会使用"=="。

int a = 5;
int b = 6;
bool c = true;
if (a == b){
c = true
}
else{
c = false
}

当"a"和"b"等于时,这段代码给出 true。

最新更新