List转换字典去重问题

时间:2019-05-03 00:13:04   收藏:0   阅读:157

数据源

技术分享图片
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"},
};
View Code

1.使用HashSet去重再ToDictionary

技术分享图片
var hash = new HashSet<int>();
var dict = list.Where(n=>!hash.Add(n.Id)).ToDictionary(key => key.Id, value => value.Name);
View Code

2.使用ToLookup(类似于一对多的字典)

var lookup = list.ToLookup(key => key.Id, value => value.Name);

 

原文:https://www.cnblogs.com/LiuNew/p/10803893.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!