开发者

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

Countr开发者_JAVA百科y

US

UK

Canada

City

CityC

CityF

CityA

CityB

CityG

CityD

CityE

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

Eg:

Canada - 2459

UK - 3243

US - 3564


var 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 !

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜