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
Countr开发者_JAVA百科y
US
UK CanadaCity
CityC
CityF CityA CityB CityG CityD CityEI 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
Eg:
Canada - 2459
UK - 3243 US - 3564var countryAvgs = countries
.Select(c => new { Id = c.CountryId, Area = c.city.Average(ct => (double)ct.sqkm)});
You should be able to do something like this (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
}
try
countries.Sum(x => x.city.Sum(y => y.sqkm)) / countries.Sum(x => x.city.Count())
Seems to work ok in LinqPad !
精彩评论