我刚刚开始学习 linq 和 lambda 表达式,它们似乎非常适合在复杂的对象集合中查找重复项,但我有点困惑,希望有人可以帮助我回到快乐编码的道路上。
我的对象的结构类似于 list.list.uniqueCustomerIdentifier
我需要确保整个复杂对象中没有重复的 uniqueCustomerIdentifier 。 如果存在重复项,我需要确定哪些是重复项并返回重复项列表。
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.
My object is structured like list.list.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.
发布评论
评论(3)
有一个 linq 运算符 Distinct( ),如果您只需要 id,它允许您过滤到一组不同的记录。 如果您已将类设置为覆盖 equals you 或具有 IEqualityComparer您可以直接调用 Distinct 扩展方法来返回列表中的唯一结果。 作为额外的好处,您还可以使用 Union 和 Intersect 方法在两个列表之间进行合并或过滤。
另一种选择是按 id 分组,然后选择第一个元素。
There is a linq operator Distinct( ), that allows you to filter down to a distinct set of records if you only want the ids. If you have setup your class to override equals you or have an IEqualityComparer you can directly call the Distinct extension method to return the unique results from the list. As an added bonus you can also use the Union and Intersect methods to merge or filter between two lists.
Another option would be to group by the id and then select the first element.
如果您想要展平两个列表层次结构,请使用
SelectMany
方法将IEnumerable>
展平为IEnumerable
>。If you want to flatten the two list hierarchies, use the
SelectMany
method to flatten anIEnumerable<IEnumerable<T>>
intoIEnumerable<T>
.