从LINQ中选择new创建对象列表

时间:2018-02-27 14:55:23

标签: c# linq generics

为什么第一个linq查询有效,但第二个没有?

var locations =
    from routeLocation in db.Table<RouteLocation>()
    join location in db.Table<Location>() on routeLocation.LocationId equals location.Id
    where functionalLocation.RouteId == routeId
    select new Location() { Id = location.Id, ParentId = location.ParentId, 
                            Name = location.Name 
                          };


var locations =  
    from routeLocation in db.Table<RouteLocation>()
    join location in db.Table<Location>() on routeLocation.LocationId equals location.Id
    where functionalLocation.RouteId == routeId
    select new { Location = location };

第二个查询的编译器错误是:

  

无法隐式转换类型   'System.Collections.Generic.List&lt;&lt;匿名类型:位置位置&gt;&gt;'   到'System.Collections.Generic.List&lt; Location&gt;

我尝试将var声明为List of Location,但仍然会得到相同的错误。我是否可以在第二个示例中使用语法,而不必像第一个示例中那样指定每个属性?

1 个答案:

答案 0 :(得分:1)

第二个查询按new {...}创建一个新的匿名类型。因此,locations的类型是此匿名类型的IEnumerable,您re probably trying to cast into a列出`会产生显示的错误。

如果要创建新Location对象的列表,则需要在类Location中创建一个复制构造函数(即具有签名Location(Location location)的构造函数,该构造函数将复制所有对象给定Location的字段到新的字段中。然后您可以将查询更改为以下内容:

var locations =  
    from routeLocation in db.Table<RouteLocation>()
    join location in db.Table<Location>() on routeLocation.LocationId equals location.Id
    where functionalLocation.RouteId == routeId
    select new Location(location);

这会产生IEnumerable<Location>,可以通过List<Location>方法将其转换为ToList()