从列表中删除具有重复属性的对象 [英] Remove objects with a duplicate property from List

查看:107
本文介绍了从列表中删除具有重复属性的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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:

fooArray.GroupBy(x => x.Id).Select(x => x.First());

这将根据Id属性对数组进行分组,然后在分组中选择第一个条目.

That will group the array by the Id property, then select the first entry in the grouping.

这篇关于从列表中删除具有重复属性的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆