简体   繁体   English

从 LINQ 创建对象列表 select new

[英]Creating a list of objects from LINQ select new

Why does the first linq query work, but the second one does not?为什么第一个 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 };

The compiler error for the second query is:第二个查询的编译器错误是:

Cannot implicitly convert type 'System.Collections.Generic.List<<anonymous type: Location Location>>' to 'System.Collections.Generic.List<Location>无法将类型 'System.Collections.Generic.List<<anonymous type: Location Location>>' 隐式转换为 'System.Collections.Generic.List<Location>

I tried declaring the var as a List of Location instead, but still get the same error.我尝试将 var 声明为位置列表,但仍然出现相同的错误。 Is it possible for me to use the syntax in the second example, instead of having to specify each property as in the first example?我是否可以使用第二个示例中的语法,而不必像第一个示例那样指定每个属性?

The second query creates a new anonymous type by new {...} .第二个查询通过new {...}创建一个新的匿名类型。 The type of locations is therefore an IEnumerable of this anonymous type which you re probably trying to cast into a List` which produces the shown error.因此, locations类型是这种匿名类型的IEnumerable ,您re probably trying to cast into a List`,从而产生显示的错误。

If you want to create a list of new Location objects, then you need to create a copy constructor in the class Location (ie a constructor with the signature Location(Location location) which copies all fields of the given Location into the new one. Then you can change your query to the following:如果你想创建一个新的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);

This yields an IEnumerable<Location> which can be converted to an List<Location> by means of the ToList() method.这会产生一个IEnumerable<Location> ,它可以通过ToList()方法转换为List<Location>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM