c# - 如何在 C# 中找出字典值的并集?

标签 c# dictionary

我需要找出字典值的并集。我在下面创建了字典。

Dictionary<int, List<string>> dict = new Dictionary<int, List<string>>();
List<string> ls1 = new List<string>();
ls1.Add("1");
ls1.Add("2");
ls1.Add("3");
ls1.Add("4");

List<string> ls2 = new List<string>();

ls2.Add("1");
ls2.Add("5");
dict.Add(1, ls1);
dict.Add(2, ls2);

所以在这种情况下输出将是 {"1","2","3","4","5"}

最佳答案

作为 Dictionary<TKey, TValue>工具 IEnumerable<KeyValuePair<TKey, TValue>>你可以使用 Linq。

下面的 Linq 会得到你想要的:

dict.SelectMany(kvp => kvp.Value).Distinct()

SelectMany将选择列表的所有元素,Distinct()确保重复的元素只返回一次。

如评论中所述,您需要 List<string>结果的一部分,因此代码可以扩展为:

var result = dict.SelectMany(kvp => kvp.Value).Distinct().ToList();

关于c# - 如何在 C# 中找出字典值的并集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28136436/

相关文章:

c# - 如果我可以只定义一个变量,为什么要使用 It.is<> 或 It.IsAny<>?

c# - 基于其他参数的必需参数

c# - 带有 Group By 和带有 Min(string) 的 Having 子句的 LINQ

python - python 中字典条目的空合并

C++:多键映射

python - 字典的稀疏数组 - 高效表示

c# - ReSharper 9 添加菜单项操作不起作用

c# - 如何通过 Xamarin.Android 中的单个 Activity 通过单击按钮在 View 之间导航?

c++ - 如何在 C++ 中使用对索引加速映射?

python - 如何通过列表中的值获取作为字典值的列表?