计算平均每组
问题描述:
我使用下面的类计算平均每组
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
答
var countryAvgs = countries
.Select(c => new { Id = c.CountryId, Area = c.city.Average(ct => (double)ct.sqkm)});
答
你应该能够做一些事情像这样(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
}
答
尝试
countries.Sum(x => x.city.Sum(y => y.sqkm))/countries.Sum(x => x.city.Count())
似乎在LinqPad中工作正常!
非常感谢..它工作...你能帮助我在这个线程上http://stackoverflow.com/questions/2872617/ordering-group-of-records使用表达式语法 – Gokul 2010-05-20 11:27:27
你用c.city 。平均在这里..如果使用类似的查询,我想访问c.city.sqkm? – Gokul 2010-05-20 11:34:16