'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?
Solution 1:[1]
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();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Serhii |
