这两个主题的链接:
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.Field
和 select 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 == null
和obj.City == null
。
关于c# - select r.Field 和 select new {r.Field} 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11520391/