使用Linq或Lambda表达式检查复杂对象中的重复项 [英] Checking for duplicates in a complex object using Linq or Lambda expression
问题描述
我刚刚开始学习linq和lambda表达式,它们似乎非常适合在复杂的对象集合中查找重复项,但是我有些困惑,希望有人可以帮助我重新走上正轨进行快乐的编码.
I've just started learning linq and lambda expressions, and they seem to be a good fit for finding duplicates in a complex object collection, but I'm getting a little confused and hope someone can help put me back on the path to happy coding.
我的对象的结构类似于list.list.uniqueCustomerIdentifier
My object is structured like list.list.uniqueCustomerIdentifier
我需要确保在整个复杂对象中没有重复的uniqueCustomerIdentifier.如果有重复项,我需要确定哪些重复项并返回重复项列表.
I need to ensure there are no duplicate uniqueCustomerIdentifier with in the entire complex object. If there are duplicates, I need to identify which are duplicated and return a list of the duplicates.
推荐答案
- 解开层次结构
- 将每个元素投影到其uniqueID属性
- 对这些ID进行分组
- 按元素多于1个的组过滤组
- 将每个组投影到该组的键(返回到uniqueID)
- 枚举查询并将结果存储在列表中.
- Unpack the hierarchy
- Project each element to its uniqueID property
- Group these ID's up
- Filter the groups by groups that have more than 1 element
- Project each group to the group's key (back to uniqueID)
- Enumerate the query and store the result in a list.
var result =
myList
.SelectMany(x => x.InnerList)
.Select(y => y.uniqueCustomerIdentifier)
.GroupBy(id => id)
.Where(g => g.Skip(1).Any())
.Select(g => g.Key)
.ToList()
这篇关于使用Linq或Lambda表达式检查复杂对象中的重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!