fifamaniac04
fifamaniac04

Reputation: 2383

nested foreach as LINQ with chained linked List

I have a List within a list. I only need the one value from the list and can do obtain my result with a nested foreach but I want to use a LINQ query of some sort.

my code:

var myCity = from c in CountryLists
           select (from city in c.stateList
                   where city.name == passedInValue
                   select city.name).FirstorDefault();

This returns myCity as a list of some sort with all values as null EXCEPT for where the match was found.

i don't want to have to walk through the city list to find the name. How can I have only one value in myCity; either null or the desired name?

Upvotes: 2

Views: 404

Answers (3)

BradleyDotNET
BradleyDotNET

Reputation: 61369

First, use SelectMany to flatten the list, then FirstOrDefault to filter:

CountryList.SelectMany(c => c.stateList).FirstOrDefault(d => d.Name == passedInValue);

Note that because FirstOrDefault can take a predicate, you don't actually need the Where clause.

Upvotes: 4

Honza Brestan
Honza Brestan

Reputation: 10957

You can use SelectMany as other have pointed out (and I prefer that solution myself), however if you'd like the query syntax, you can use multiple from clauses (check the MSDN documentation for more examples):

var city = (from c in CountryLists
            from city in c.stateList
            where city.name == passedInValue
            select city.name).FirstOrDefault();

It is equivalent to the SelectMany method solution, it uses it under the covers anyway.

Upvotes: 1

Selman Genç
Selman Genç

Reputation: 101701

How about using SelectMany:

var city = CountryLists
           .SelectMany(x => x.stateList)
           .FirstOrDefault(x => x.name == passedInValue);

Upvotes: 4

Related Questions