Smithy
Smithy

Reputation: 2190

Get ICollection out from IQueryable<ICollection> LINQ Query

I'm trying to write a query that grabs a list of countries out from my joined data. Places is List<Country>.

        var zonedCountries = (from dz in db.DeliveryZones.Include(d => d.Places)
                              where model.DeliveryZones.Contains(dz.ID)
                              select dz.Places);

I would expect zonedCountries to be a List but instead it is a IQueryable<ICollection<Country>>.

How do I extract the list from this?

Upvotes: 2

Views: 1949

Answers (1)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236328

If you want to get flattened list of countries:

var zonedCountries = (from dz in db.DeliveryZones.Include(d => d.Places)
                      where model.DeliveryZones.Contains(dz.ID)
                      from p in dz.Places
                      select p);

Or use SelectMany:

var zonedCountries = db.DeliveryZones.Include(d => d.Places)
                       .Where(dz => model.DeliveryZones.Contains(dz.ID))
                       .SelectMany(dz => dz.Places);

BTW I'm not sure if you need to include places manually in this case (thus you are selecting places instead of delivery zones). And you will probably want to select distinct countries only - Distinct() will help you here. Also if you want to store results in list, then simple ToList() call will do the job.

Upvotes: 12

Related Questions