c# - select r.Field 和 select new {r.Field} 的区别

标签 c# linq entity-framework linq-to-sql c#-4.0

这两个主题的链接:

Convert Lambda Expression of a query to linq version

return items that all records related to that items have specific conditions

在第一个主题@xanatos 中评论说:

@Kerezo Be aware that the new { r.City } error appears twice (once in each query). new { r.City } creates an anonymous object with a single property called City that contains the City object (so you are wrapping your City in an object) Without the new you have directly the City

考虑这段代码:

var citiesToExclude = from r in ent.TestAllStatusEqualsOnes
                              where r.Status != 1
                              select r.City;

GridView1.DataSource = citiesToExclude;
GridView1.DataBind();

如果我这样写这段代码:

var citiesToExclude = from r in ent.TestAllStatusEqualsOnes
                              where r.Status != 1
                              select new { r.City };

GridView1.DataSource = citiesToExclude;
GridView1.DataBind();

凡事平等。

我不明白 select r.Fieldselect new {r.Field} 之间有什么区别。任何人都可以解释更多吗?

谢谢

最佳答案

匿名类型与任何其他类型几乎相同。所以:

select new { r.City }

与以下内容几乎相同:

select new SomeType { City = r.City}

与:

class SomeType { public string City {get;set;} }

这样一来,也许可以使区分变得简单;它与以下之间的区别相同:

string x = obj.City;

SomeType y = new SomeType { City = obj.City };

在一种情况下,您获取的是城市名称。在另一种情况下,您正在获取一个对象,该对象具有一个名为 City 的属性,城市名称(尽管它可以,一般来说case,也有其他属性)。

同样的逻辑适用于 LINQ。

两者之间的一个方便区别是考虑 null,例如:

var city = {some query}.FirstOrDefault();

如果您选择的是实际的城市名称,则很难区分“无行”与“一行,城市名称为空”。如果您选择一个对象,您可以区分obj == nullobj.City == null

关于c# - select r.Field 和 select new {r.Field} 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11520391/

相关文章:

c# - 为什么我的 CreateRibbonExtensibilityObject 方法没有被调用?

c# - 如何仅 Ping IPv4?

c# - 寻找最大问题

c# - 使用 Entity Framework 等 ORM 更新数据库中保存的数据的方法是什么?

c# - Entity Framework 错误 - 查询语法无效

c# - WPF Slider - 当值从 UI 更改时通知

c# - ASP.NET WebForms 设计模式

c# - LINQ 连接具有不同类型的多个条件

c# - 使用 LINQ 大写对象列表

c# - 如何在 MVC4 的 UserProfile 中创建自定义附加字段