Accessing child collection in query
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 = count开发者_运维百科ries
.Select(c => new { Id = c.CountryId, Area = c.City.sqkm???});
c.city.sqkm
gives compilation error...how to modify query
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
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);
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});
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})
if you want all sqkm from all cities in all contries SelectMany() is your friend.
countries.SelectMany(country => country.Cities).Select(city => city.sqkm);
var countryQuery = countries
.Select(c => c.City.Foreach(city => new { Id = c.CountryId, Area = city.sqkm } ));
精彩评论