LINQ查询 - 如何使用Select将结果集映射到另一个对象

foz*_*let 5 c# linq

我有一个对象层次结构,排列为Continents> Countries> Cities.能够选择特定"国家/地区"中的所有城市,如下所示.我正在寻找的是一种合并这两个查询的方法,并在单个查询中到达cityList.

var cities = network.Continents
    .SelectMany(continent => continent.Countries)
    .Where(ctry => ctry.Id == "country")
    .SelectMany(ctry => ctry.Cities);

List<City> cityList = (from c in cities
                        select new City { Id = c.Id, Name = c.Name }).ToList<City>();
Run Code Online (Sandbox Code Playgroud)

"城市中的c"具有与cityList中的结构不同的结构,因此具有与第二查询中的映射不同的结构.

Sae*_*iri 11

只需在查询中使用点表示法:

var cities = network.Continents
    .SelectMany(continent => continent.Countries)
    .Where(ctry => ctry.Id == "country")
    .SelectMany(ctry => ctry.Cities)
    .Select(cty=> new City{Id = cty.Id, Name = cty.Name }).ToList<City>();
Run Code Online (Sandbox Code Playgroud)

我认为它是可读的,并且没有额外的开销,生成的sql查询在大多数情况下都是类似的,你可以这样做,所以只是可读性很重要.


Jef*_*ado 5

你应该能做到这一点:

var cityList = network.Continents
    .SelectMany(continent => continent.Countries)
    .Where(ctry => ctry.Id == "country")
    .SelectMany(ctry =>
        ctry.Cities.Select(c => new City { Id = c.Id, Name = c.Name })
    ).ToList();
Run Code Online (Sandbox Code Playgroud)

或者:

var cityList =
    (from continent in network.Continents
     from country in continent.Countries
     where country.Id == "country"
     from city in country.Cities
     select new City { Id = city.Id, Name = city.Name })
    .ToList();
Run Code Online (Sandbox Code Playgroud)


Jon*_*eet 5

发布选项的另一种替代方案:

var cityList = network.Continents
                      .SelectMany(continent => continent.Countries)
                      .Where(ctry => ctry.Id == "country")
                      .SelectMany(ctry =>  ctry.Cities,
                                  c => new City { Id = c.Id, Name = c.Name })
                      .ToList();
Run Code Online (Sandbox Code Playgroud)

SelectMany(第二次调用中)的重载是C#编译器在查询表达式中使用的重载.请注意,如果要将其编写为查询表达式,则可以轻松地执行此操作:

var cityList = (from continent in network.Continents
                from country in continent.Countries
                where country.Id == "country"
                from city in country.Cities
                select new City { Id = city.Id, Name = city.Name }).ToList(); 
Run Code Online (Sandbox Code Playgroud)

在LINQ to对象的查询表达式会稍微高于此特定情况下的点标记格式效率较低,因为大陆和国家范围变量将被向下传播到SELECT子句...但是我希望通过任何生成的SQL数据库LINQ提供程序是相同的,甚至在LINQ to Objects内部的差异很可能是微不足道的.

请注意,调用时不需要指定类型参数ToList- 类型将被推断为City已经.