数据源
var list = new List<TestClass> { new TestClass{Id=1,Name="1"}, new TestClass{Id=2,Name="2"}, new TestClass{Id=3,Name="3"}, new TestClass{Id=4,Name="4"}, new TestClass{Id=5,Name="5"}, new TestClass{Id=1,Name="9"}, };
1.使用HashSet去重再ToDictionary
var hash = new HashSet<int>(); var dict = list.Where(n=>!hash.Add(n.Id)).ToDictionary(key => key.Id, value => value.Name);
2.使用ToLookup(类似于一对多的字典)
var lookup = list.ToLookup(key => key.Id, value => value.Name);
原文:https://www.cnblogs.com/LiuNew/p/10803893.html