C# 计算各组的平均值

C# 计算各组的平均值,c#,linq,C#,Linq,我正在使用下面的类 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;} } 国家级 { int CountryID{get;set;} 列表城市{get;set;} } 阶级城市 { in

我正在使用下面的类

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;}
}
国家级
{
int CountryID{get;set;}
列表城市{get;set;}
}
阶级城市
{
int CountryID{get;set;}
字符串城市{get;set;}
int sqkm{get;set;}
}
这是一些国家和城市的样本数据

国家

美国
英国
加拿大

城市

城市社区
CityF
城市
城巴
城市G
CityD
城市

我正在使用

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
List countries=newlist{new Country(){CountryID=“US”,city=newlist{new city(){CountryID=“US”,city=“CityF”,sqkm=2803},依此类推
问题1:我想使用LINQ查找每个国家的平均平方公里土地

例如:

加拿大-2459
英国-3243

US-3564

您应该能够使用System.Linq;执行类似操作:

试一试


在LinqPad中似乎可以正常工作!

非常感谢..它工作了..您可以使用表达式syntax在这个线程上帮助我吗您在这里使用了c.city.Average..如果使用类似的查询,我想访问c.city.sqkm怎么办?
foreach( Country c in countries)
{
  int average = c.city.Sum( city => city.sqkm)/c.city.Count();
  // display it, or save it, or something
}
var countryAvgs = countries
    .Select(c => new { Id = c.CountryId, Area = c.city.Average(ct => (double)ct.sqkm)});
countries.Sum(x => x.city.Sum(y => y.sqkm)) / countries.Sum(x => x.city.Count())