如何在C#中找到字典值的联合?

Viv*_*ain 2 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);
Run Code Online (Sandbox Code Playgroud)

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

Luk*_*oid 6

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

以下Linq会得到你的意思:

dict.SelectMany(kvp => kvp.Value).Distinct()
Run Code Online (Sandbox Code Playgroud)

SelectMany将选择所有列出的元素,在Distinct()保证重复的元素只返回一次.

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

var result = dict.SelectMany(kvp => kvp.Value).Distinct().ToList();
Run Code Online (Sandbox Code Playgroud)