展平包含单个项目的列表列表

Aki*_*ira 5 c# linq

我有一个由最多包含单个字符串的列表组成的列表,例如:

var fruits = new List<List<string>>
{
    new List<string>(),
    new List<string> { "Apple" },
    null,
    new List<string> { "Banana" },
};
Run Code Online (Sandbox Code Playgroud)

我想从上面的列表中提取字符串,不允许包含字符串的列表有多个项目。也就是说,我需要得到以下结果:

{ "Apple", "Banana" }
Run Code Online (Sandbox Code Playgroud)

到目前为止,我一直在尝试以下操作:

var result = fruits
    .Where(x => x != null)
    .Select(x => x.SingleOrDefault())
    .Where(x => x != null);
Run Code Online (Sandbox Code Playgroud)

有没有更简单的解决方案来做到这一点?

Ser*_*hii 3

如果我理解正确,您想要将列表中的所有唯一项目选择到单个列表中,您可以使用SelectMany()和 来Distinct()实现:

fruits.Where(x=> x != null).SelectMany(x=> x).Distinct();
Run Code Online (Sandbox Code Playgroud)