c# - ef 中的奇怪语法

标签 c# .net linq lambda entity-framework-6

 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/

相关文章:

c# - 将值设置为列表 c# 中的 [Flags] 枚举

c# - 如何使用Observablecollection制作列表数据以显示在列表框中

c# - 如何在不使用 Linq 的情况下将 IList<string> 转换为 string[]

c# - 如何创建一个可以在其中放置其他控件的 UserControl?

c# - 我怎样才能结合这些线?

c# - InvalidOperationException - TwoWay 或 OneWayToSource 绑定(bind)无法对只读属性起作用

c# - HKEY_USERS 仅包含登录用户

c# - 如何获得参赛作品的版权属性

c# - 动态 LINQ 到数据表 : why using hardcode string "it" as DataRow

c# - 在 Linq 中使用 .NET 4 动态关键字的好例子?