【发布时间】:2019-06-04 11:18:39
【问题描述】:
我有一个可枚举的对象列表。
该对象具有以下属性: -ID -姓名 -类型
我想收集那些在列表中具有相同名称和类型的对象的 ID。
【问题讨论】:
标签: c# duplicates enumerable
我有一个可枚举的对象列表。
该对象具有以下属性: -ID -姓名 -类型
我想收集那些在列表中具有相同名称和类型的对象的 ID。
【问题讨论】:
标签: c# duplicates enumerable
要在集合中搜索重复项(基于两个字段-Name and Type)并检索第三个字段 (ID),您需要首先将问题分解为多个部分。
1) 查找重复项
list.GroupBy(x=>new{x.Name,x.Type})
list.GroupBy(x=>new{x.Name,x.Type}).Where(x=>x.Count()>1)
2) 选择 ID
list.GroupBy(x=>new{x.Name,x.Type})
.Where(x=>x.Count()>1)
.SelectMany(x=>x.ToList())
选择 ID
list.GroupBy(x=>new{x.Name,x.Type})
.Where(x=>x.Count()>1)
.SelectMany(x=>x.ToList()).Select(x=>x.ID)
例如,将它们放在一起,
var list = new List<CustomObject>
{
new CustomObject{ID=1, Name="Abc",Type="Type1"},
new CustomObject{ID=2, Name="Def",Type="Type2"},
new CustomObject{ID=3, Name="Abc",Type="Type1"},
new CustomObject{ID=4, Name="Abc",Type="Type2"},
new CustomObject{ID=5, Name="Def",Type="Type2"},
new CustomObject{ID=6, Name="Def",Type="Type1"},
};
var result = list.GroupBy(x=>new{x.Name,x.Type})
.Where(x=>x.Count()>1)
.SelectMany(x=>x.ToList()).Select(x=>x.ID);
上面例子的输出
1
3
2
5
【讨论】:
使用 Linq .GroupBy() 它将创建一个列表列表,其中每个列表都由一个键组织。
list.GroupBy(e => new { e.Name, e.Type })
【讨论】:
使用 Linq 和 group 按名称和类型对所有对象进行分组,然后只取 Count > 1 的对象。
var group = from myObject o in myObjects
group new { p.Name, p.Type } into grp
select new { Name = grp.Key.Name, Type = grp.Key.Type, Count = grp.Count() };
var dups = group.Where(g=>g.Count >1);
【讨论】: