Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
294 views
in Technique[技术] by (71.8m points)

c# - Creating a list of objects from LINQ select new

Why does the first linq query work, but the second one does not?

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>

I tried declaring the var as a List of Location instead, but still get the same error. 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The second query creates a new anonymous type by new {...}. The type of locations is therefore an IEnumerable of this anonymous type which youre probably trying to cast into aList` which produces the shown error.

If you want to create a list of new Location objects, then you need to create a copy constructor in the class Location (i.e. 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:

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...