我有一个由最多包含单个字符串的列表组成的列表,例如:
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)
有没有更简单的解决方案来做到这一点?
如果我理解正确,您想要将列表中的所有唯一项目选择到单个列表中,您可以使用SelectMany()和 来Distinct()实现:
fruits.Where(x=> x != null).SelectMany(x=> x).Distinct();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
288 次 |
| 最近记录: |