✅ Nested from clause in query syntax
Hello guys, can someone explain the use of the nested
from clause in the code above please. Why do we use nested from? Couldn't we just use the dot notation, like country.Cities? Why would it matter here?C#
var largeCitiesList = (
from country in countries
from city in country.Cities
where city.Population > 10000
select city
).ToList();
// or split the expression
IEnumerable<City> largeCitiesQuery =
from country in countries
from city in country.Cities
where city.Population > 10000
select city;
var largeCitiesList2 = largeCitiesQuery.ToList();from{} I'm confused about thatrecord ?record supplies a ToString that does that.var query = (from country in countries
select country).ToList();List<Country>
[
{
Name = "USA",
Cities =
[
{ Name = "New York", Population = 8419600 },
{ Name = "Los Angeles", Population = 3980400 },
{ Name = "Smalltown", Population = 8000 }
]
},
{
Name = "Canada",
Cities =
[
{ Name = "Toronto", Population = 2930000 },
{ Name = "Vancouver", Population = 631000 }
]
}
]C#
City[] cities = [
new City("Tokyo", 37_833_000),
new City("Delhi", 30_290_000),
new City("Shanghai", 27_110_000),
new City("São Paulo", 22_043_000)
];
//Query syntax
IEnumerable<City> queryMajorCities =
from city in cities
where city.Population > 30_000_000
select city;
// Execute the query to produce the results
foreach (City city in queryMajorCities)
{
Console.WriteLine(city);
}
// Output:
// City { Name = Tokyo, Population = 37833000 }
// City { Name = Delhi, Population = 30290000 }
// Method-based syntax
IEnumerable<City> queryMajorCities2 = cities.Where(c => c.Population > 30_000_000);
// Execute the query to produce the results
foreach (City city in queryMajorCities2)
{
Console.WriteLine(city);
}
// Output:
// City { Name = Tokyo, Population = 37833000 }
// City { Name = Delhi, Population = 30290000 }{}C#
record City(string Name, long Population);
record Country(string Name, double Area, long Population, List<City> Cities);
record Product(string Name, string Category);recordrecordToStringvar largeCities = countries
.SelectMany(country => country.Cities)
.Where(city => city.population > 10000)
.ToList();var largeCitiesList = countries
.SelectMany(c => c.Cities)
.Where(c => c.Population > 10_000)
.ToList();var query = (from country in countries
select country).ToList();var query = countries.ToList();