[英]Calculate average in each group
I am using the following class 我正在使用以下课程
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;}
}
Here's is some sample data for Country and City 这是国家和城市的一些示例数据
Country 国家
US 我们
UK 英国
Canada 加拿大
City 市
CityC 城市C
CityF 城市F
CityA 城市A
CityB 城市B
CityG 城市G
CityD 城市D
CityE 城市E
I am populating using 我正在使用
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
Question 1: I want to use LINQ to find avg sq. km of land per country 问题1:我想使用LINQ查找每个国家/地区的平均平方公里土地
Eg: 例如:
Canada - 2459 加拿大-2459
UK - 3243 英国-3243
US - 3564 美国-3564
You should be able to do something like this ( using System.Linq;
): 您应该能够执行以下操作( 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
}
var countryAvgs = countries
.Select(c => new { Id = c.CountryId, Area = c.city.Average(ct => (double)ct.sqkm)});
try 尝试
countries.Sum(x => x.city.Sum(y => y.sqkm)) / countries.Sum(x => x.city.Count())
Seems to work ok in LinqPad ! 似乎可以在LinqPad中正常工作!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.