2010-05-20 191 views
0

我使用下面的類計算平均每組

class Country 
{ 
    int CountryID {get; set;} 
    List<City> city {get; set;} 
} 

class City 
{ 
    int CountryID {get; set; } 
    string city {get; set;} 
    int sqkm {get; set;} 
} 

這裏是國家和城市

國家

美國
英國
加拿大

一些示例數據

CityC
CityF
CityA
CityB
CityG
CityD
CityE

我使用

List<Country> countries = new List<Country> { new Country() { CountryID = "US", city = new List<City> { new City() {CountryID = "US", City ="CityF", sqkm = 2803 }, and so on 

問題1填充:我想使用LINQ發現平均平方的每個國家土地

EG公里。

加拿大 - 2459
英國 - 3243
美國 - 3564

回答

0
var countryAvgs = countries 
    .Select(c => new { Id = c.CountryId, Area = c.city.Average(ct => (double)ct.sqkm)}); 
+0

非常感謝..它工作...你能幫助我在這個線程上http://stackoverflow.com/questions/2872617/ordering-group-of-records使用表達式語法 – Gokul 2010-05-20 11:27:27

+0

你用c.city 。平均在這裏..如果使用類似的查詢,我想訪問c.city.sqkm? – Gokul 2010-05-20 11:34:16

0

你應該能夠做一些事情像這樣(using System.Linq;):

foreach(Country c in countries) 
{ 
    int average = c.city.Sum(city => city.sqkm)/c.city.Count(); 
    // display it, or save it, or something 
} 
0

嘗試

countries.Sum(x => x.city.Sum(y => y.sqkm))/countries.Sum(x => x.city.Count()) 

似乎在LinqPad中工作正常!