从IQueryable <ICollection> LINQ Query中获取ICollection

Smi*_*thy 2 c# linq entity-framework

我正在尝试编写一个查询,从我加入的数据中获取国家列表. PlacesList<Country>.

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

我希望zonedCountries成为一个列表,但它是一个IQueryable<ICollection<Country>>.

如何从中提取列表?

Ser*_*kiy 11

如果你想获得扁平的国家列表:

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

或使用SelectMany:

var zonedCountries = db.DeliveryZones.Include(d => d.Places)
                       .Where(dz => model.DeliveryZones.Contains(dz.ID))
                       .SelectMany(dz => dz.Places);
Run Code Online (Sandbox Code Playgroud)

顺便说一下,我不确定在这种情况下是否需要手动包含场所(因此您选择的是场所而不是交付区域).你可能只想选择不同的国家 - Distinct()在这里会帮助你.此外,如果您想将结果存储在列表中,那么简单的ToList()调用将完成这项工作.