c# - 如何从 C# 中的列表列表中获取不同的元素

标签 c# linq list

我有一个列表列表,其中子列表是字符串列表。我期待的结果是所有不同字符串的列表。 例如:

var listoflist = new List<List<string>> { new List<string> { "A", "B", "C" },
                                          new List<string> { "A", "B", "D", "E" } };

对于上面的列表,我期望输出为 {"A","B","C","D","E"}

这是我找到的解决方案,但我觉得它不是一个有效的解决方案。请提供您对此的想法。

var listoflist = new List<List<string>> { new List<string> { "A", "B", "C" },
                                          new List<string> { "A", "B", "D", "E" } };

List<string> distinctList = new List<string>();
listoflist.ForEach(list =>
{
    distinctList.AddRange(list);
});

distinctList = distinctList.Distinct().ToList();

最佳答案

您可以使用 Enumerable.SelectMany 展平列表:

var list = listoflist.SelectMany(x => x).Distinct();

如果你想具体化查询并得到一个List<string> , 添加 ToList() .

关于c# - 如何从 C# 中的列表列表中获取不同的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34313041/

相关文章:

c# - 模型外的 ASP Net MVC 中的业务逻辑

C# Linq to XML,当 child 满足条件时获取 parent

c# - 如何在 C# 中使用 LINQ 从 ListView 中删除项目

python - 由于某种原因,即使该项目在范围内,我仍然收到索引错误

c# - 如何读取WebClient的自定义 header 条目

c# - NUnit基类

c# - 从 C# 将数据传入和传出 DLL

c# - 根据条件和发生将集合拆分为对象

r - 如何查看列表的任何元素是否仅包含 R 中的某个值

python追加奇怪的行为