I have an object hierarchy arranged as Continents > Countries > Cities. Am able to select all the cities in a specific "country" as below. What I am looking for is a way to merge these two queries, and arrive at the cityList in a single query.
var cities = network.Continents
.SelectMany(continent => continent.Countries)
.Where(ctry => ctry.Id == "country")
.SelectMany(ctry => ctry.Cities);
List<City> cityList = (from c in cities
select new City { Id = c.Id, Name = c.Name }).ToList<City>();
The "c in cities" have a different structure from the one in cityList and hence the mapping in the second query.
select new EmailAddress(entry.Name, entry. Email); creates a new EmailAddress object that contains the name and e-mail address obtained from a ContactInfo object in the contacts array. new EmailAddress objects are created by the query in its select clause, during the query's execution.
The Select() method invokes the provided selector delegate on each element of the source IEnumerable<T> sequence, and returns a new result IEnumerable<U> sequence containing the output of each invocation.
Language-Integrated Query (LINQ) makes it easy to access database information and execute queries. By default, LINQ queries return a list of objects as an anonymous type. You can also specify that a query return a list of a specific type by using the Select clause.
Yes it supports General Arrays, Generic Lists, XML, Databases and even flat files. The beauty of LINQ is uniformity. Now, how does it provide uniformity? Using a single LINQ query you can process data in various data sources.
Just use dot notation in your query:
var cities = network.Continents
.SelectMany(continent => continent.Countries)
.Where(ctry => ctry.Id == "country")
.SelectMany(ctry => ctry.Cities)
.Select(cty=> new City{Id = cty.Id, Name = cty.Name }).ToList<City>();
I think it's readable, and it doesn't have extra overhead; usually, the generated SQL query is similar to what you may write on your own, hence the readability of this one is its advantage.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With