Alan2
Alan2

Reputation: 24572

How can I flatten out a list that contains another list using LINQ?

I have a List of IJapaneseDictionaryEntry objects which are described below. Inside this are IKanji objects.

public interface IJapaneseDictionaryEntry
{
    int Sequence { get; }
    IEnumerable<IKanji> Kanjis { get; }
    IEnumerable<IReading> Readings { get; }
    IEnumerable<ISense> Senses { get; }
}

Where each object contains a list of IKanji objects

public interface IKanji
{
    string Text { get; }
    IEnumerable<KanjiInformation> Informations { get; }
    IEnumerable<Priority> Priorities { get; }
}

List<IJapaneseDictionaryEntry> entries = dictionary.GetEntries().ToList();

Can someone show me how it's possible to get a list of all the Text values in the Kanjis lists?

In other words if there are two objects in entries and the first has a Kanjis list with three entries and the second a Kanjis list with two entries then what I would like to see is a list containing 5 rows of Kanji.Text Another way to explain it would be that I want to see a single list of every Kanji.Text in entries

Upvotes: 0

Views: 62

Answers (1)

Mun
Mun

Reputation: 14308

You can use the SelectMany method to flatten multiple lists into a single list. In this case, you could do something like this:

var items = dictionary.GetEntries()
                      .SelectMany(x => x.Kanjis)
                      .Select(x => x.Text)

Upvotes: 4

Related Questions