var items = context.Items.Where(x => x.IsActive=true).ToList();
为什么语法正确且查询有效?
最佳答案
这是代码中一个非常微妙的错误。 Where
Func 需要返回一个 bool
才有效,但您设置的是值,而不是比较它,所以没有什么可返回的,是吗?
一般说明
代码可以编译,因为当您在 C# 中赋值时,例如x = 1
该表达式被评估,因此返回,作为分配的值 (1
)。
人们有时会使用它来懒惰地实例化一个只读属性,例如
private Foo myFoo;
public Foo FooInstance
{
// set myFoo to the existing instance or a new instance
// and return the result of the "myFoo ?? new Foo()" expression
get { return myFoo = myFoo ?? new Foo(); }
}
或者将相同的值赋给多个变量:
// set z to 1
// set y to result of "z = 1"
// set x to result of "y = z = 1"
x = y = z = 1;
你的场景
因此,您对列表中的每个条目所做的操作是将 IsActive
设置为 true
并从函数返回相同的 true
。因此,您最终会得到一个包含所有条目的新列表,并且所有条目都已更改为事件状态。
如果您在 Where
中使用不是 bool
的属性,例如 int
,您会得到编译错误:
Cannot implicitly convert type 'int' to 'bool'.
以此为例 ( https://dotnetfiddle.net/9S9NAV )
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
var foos = new List<Foo>()
{
new Foo(true, 1),
new Foo(false, 2)
};
// works
var actives = foos.Where(x => x.IsActive=true).ToList();
// returns 2, not 1!
Console.WriteLine(actives.Count);
// compile error
var ages = foos.Where(x => x.Age = 1).ToList();
}
}
public class Foo {
public Foo(bool active, int age)
{
this.IsActive = active;
this.Age = age;
}
public bool IsActive { get; set; }
public int Age { get; set; }
}
关于c# - ef 中的奇怪语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34946396/