cost
cost

Reputation: 4490

Use LINQ to combine a property in a list of lists?

I have a Dictionary that looks like such: Dictionary<Search_Requests, List<Tuple<Search_Subjects, SearchData>>>

In the SearchData class, there's a property called SearchCode. What I want to do is get an array of every search code that appears in this dictionary. I could do this with a few loops, but I'd really prefer to use LINQ. Unfortunately, I can't wrap my mind around how to do this. I tried

RequestDictionary.Select(s => s.Value.Select(z => s.Value.Select(x => x.Item2.SearchCode).ToArray()).ToArray()).ToArray();

But that just got me a string[][][], which isn't close to what I wanted. Can I get a push in the right direction?

Upvotes: 6

Views: 2337

Answers (2)

Sphinxxx
Sphinxxx

Reputation: 13057

The trick is to combine .Select() and .SelectMany():

var codes = requestDictionary
               //Extract all List<>s from the dictionary and enumerate them back-to-back:
               .SelectMany(entry => entry.Value)
               //Extract the SearchCode from each list item:
               .Select(tuple => tuple.Item2.SearchCode)
               .ToArray();

Upvotes: 0

BartoszKP
BartoszKP

Reputation: 35921

You can use .SelectMany() to flatten the results:

RequestDictionary
    .SelectMany(s 
        => s.Value.SelectMany(z => s.Value.Select(x => x.Item2.SearchCode))
    .ToArray();

Upvotes: 6

Related Questions