tags:

views:

41

answers:

3

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

A: 

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
}
ANeves
A: 
var countryAvgs = countries
    .Select(c => new { Id = c.CountryId, Area = c.city.Average(ct => (double)ct.sqkm)});
Lee
Thanks so so much..it worked...can you help me on this thread too http://stackoverflow.com/questions/2872617/ordering-group-of-records using expression syntax
Gokul
You used c.city.Average here..what if using similar query, I want to access c.city.sqkm?
Gokul
A: 

try

countries.Sum(x => x.city.Sum(y => y.sqkm)) / countries.Sum(x => x.city.Count())

Seems to work ok in LinqPad !

Ed Woodcock