从 List 中删除具有重复属性的对象 [英] Remove objects with a duplicate property from List
本文介绍了从 List 中删除具有重复属性的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 C# 对象列表.所有对象都包含一个属性 ID.有几个对象具有相同的 ID 属性.
I have a List of objects in C#. All of the objects contain a property ID. There are several objects that have the same ID property.
如何在每个 ID 属性只有一个对象的情况下修剪列表(或创建新列表)?
How can I trim the List (or make a new List) where there is only one object per ID property?
[从列表中删除任何额外的重复项]
[Any additional duplicates are dropped out of the List]
推荐答案
如果你想避免使用第三方库,你可以这样做:
If you want to avoid using a third-party library, you could do something like:
var bar = fooArray.GroupBy(x => x.Id).Select(x => x.First()).ToList();
这将按 Id 属性对数组进行分组,然后选择分组中的第一个条目.
That will group the array by the Id property, then select the first entry in the grouping.
这篇关于从 List 中删除具有重复属性的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文