我需要找出字典值的并集。我在下面创建了字典。
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/