Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...