tags:

views:

36

answers:

6

I am populating a list using

List<Country> countries = new List<Country> 
{ 
   new Country() 
   {
      CountryID = "US",
      City = new List<City>
      {
         new City()
         {
            CountryID = "US", CityName = "dfdsf", sqkm = 2803
         }
      }
   }
};

and so on

How to access sqkm in the following query?

var countryQuery = countries
    .Select(c => new { Id = c.CountryId, Area = c.City.sqkm???});

c.city.sqkm gives compilation error...how to modify query

+1  A: 

If you want the first city of your list of cities, use c.city.First().sqkm

EDIT: in response to your comment, if you want every sqkm defined in every country then use:

countries.SelectMany(c => c.city)

If you want all cities per country, you already have that with only c.city since it's already a list (which should be renamed Countries to be clearer).

EDIT2: countries.SelectMany(c => c.City).Where(city => city.sqkm > 2000);

Julien Lebosquain
no i want to list all sqkm per Country
Gokul
A: 

You have to specify which list item you want either by using an index as below, or by using an extension method that returns a single record.

var countryQuery = countries
.Select(c => new { Id = c.CountryId, Area = c.city[0].sqkm})
Ben Robinson
+1  A: 

As mentioned by @Julien, if you want one, use First(); if you want the entire list, you can do:

c.city.Select(i => i.sqkm) // returns array
Brian
A: 

The city is a list, so you should define the city you want.

To get the first:

var countryQuery = countries
    .Select(c => new { Id = c.CountryId, Area = c.city.First().sqkm});
GvS
A: 
var countryQuery = countries
    .Select(c => c.City.Foreach(city => new { Id = c.CountryId, Area = city.sqkm } ));
VMAtm
A: 

if you want all sqkm from all cities in all contries SelectMany() is your friend.

countries.SelectMany(country => country.Cities).Select(city => city.sqkm);
Oliver