2011-06-07 52 views
4

我有一個對象層次結構,排列爲Continents> Countries> Cities。能夠選擇特定「國家」中的所有城市如下。我正在尋找的是一種合併這兩個查詢的方法,並在單個查詢中到達cityList。LINQ Query - 如何將結果集映射到另一個對象使用選擇

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>(); 

「城市中的c」與城市列表中的結構不同,因此第二個查詢中的映射結構也不同。

+0

在這裏找到相關問題的答案:[link](http://stackoverflow.com/questions/923238/linq-select-certain-properties-into-another-object) 'code' .Select( city => new City(){Id = city.Id,Name = city.Name})。ToList (); – fozylet 2011-06-07 06:13:26

回答

10

只需使用點符號在查詢:

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>(); 

我認爲這是可讀的,它沒有額外的開銷,生成的sql查詢在大多數情況下可以做到這一點,所以只是可讀性很重要。

+0

謝謝。我根據這個做了修改,因爲這符合我的可讀性思想。 – fozylet 2011-06-07 06:20:24

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(); 

或者:

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(); 
+0

謝謝你的回答 – fozylet 2011-06-07 06:40:37

3

嘗試以下方法:

var cities = 
    from continent in network.Continents 
    from country in continent.Countries 
    from city in country.Cities 
    where country.Id = "country" 
    select new City { Id = c.Id, Name = c.Name }; 
+0

謝謝你的回答。正在尋找點符號,因爲它更舒服。 – fozylet 2011-06-07 06:24:04

4

另一個替代選項貼:

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(); 

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(); 

在LINQ to對象的查詢表達式會比在這種特殊情況下的點標記格式效率較低,因爲大陸和國家範圍的變量會傳播到select子句......但我期望任何數據庫LINQ提供程序生成的SQL都是相同的,甚至在LINQ to Objects中,差異可能是微不足道的。

請注意,調用ToList時不需要指定類型參數 - 該類型已被推斷爲City

+0

有趣的變化。感謝您的發表。 – fozylet 2011-06-07 06:29:02

相關問題