首页 > 其他 > 详细

List转换字典去重问题

时间:2019-05-03 00:13:04      阅读:157      评论:0      收藏:0      [点我收藏+]

数据源

技术分享图片
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);

 

List转换字典去重问题

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!