Akira
Akira

Reputation: 4473

Flatten list of lists containing a single item

I have a list that consists of lists containing up to a single string, for example:

var fruits = new List<List<string>>
{
    new List<string>(),
    new List<string> { "Apple" },
    null,
    new List<string> { "Banana" },
};

I would like to extract the strings from the list above, not allowing the lists containing the strings to have more than one item. That is, I need to have the following result:

{ "Apple", "Banana" }

So far I have been trying the following:

var result = fruits
    .Where(x => x != null)
    .Select(x => x.SingleOrDefault())
    .Where(x => x != null);

Is there a simpler solution to do this?

Upvotes: 5

Views: 410

Answers (1)

Serhii
Serhii

Reputation: 753

If I understand correctly you want to select all unique items in lists to a single list, you can use SelectMany() and Distinct() for that:

fruits.Where(x=> x != null).SelectMany(x=> x).Distinct();

Upvotes: 3

Related Questions