Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ Query - How to map a resultset into another object using Select

Tags:

c#

linq

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.

like image 472
fozylet Avatar asked Jun 07 '11 06:06

fozylet


People also ask

How do you create a new object in LINQ select?

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.

What is the use of select in LINQ?

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.

What a LINQ query returns in LINQ to object?

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.

Can LINQ query work with array?

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.


1 Answers

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.

like image 73
Saeed Amiri Avatar answered Nov 25 '22 21:11

Saeed Amiri