C# 从 List 中删除具有重复属性的对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9993172/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 12:02:28  来源:igfitidea点击:

Remove objects with a duplicate property from List

c#arrays

提问by Baxter

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.

我有一个 C# 对象列表。所有对象都包含一个属性 ID。有几个对象具有相同的 ID 属性。

How can I trim the List (or make a new List) where there is only one object per ID property?

在每个 ID 属性只有一个对象的情况下,如何修剪列表(或创建一个新列表)?

[Any additional duplicates are dropped out of the List]

[从列表中删除任何额外的重复项]

采纳答案by Daniel Mann

If you want to avoid using a third-party library, you could do something like:

如果您想避免使用第三方库,您可以执行以下操作:

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

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

这将按 Id 属性对数组进行分组,然后选择分组中的第一个条目。

回答by sll

MoreLINQ DistinctBy()will do the job, it allows using object proeprty for the distinctness. Unfortunatly built in LINQ Distinct()not flexible enoght.

MoreLINQDistinctBy()将完成这项工作,它允许使用对象属性来区分。不幸的是,内置 LINQDistinct()不够灵活。

var uniqueItems = allItems.DistinctBy(i => i.Id);

DistinctBy()

DistinctBy()

Returns all distinct elements of the given source, where "distinctness" is determined via a projection and the default eqaulity comparer for the projected type.

返回给定源的所有不同元素,其中“distinctness”是通过投影和投影类型的默认相等比较器确定的。

PS: Credits to Jon Skeetfor sharing this library with community

PS:感谢Jon Skeet与社区分享这个图书馆

回答by gdoron is supporting Monica

var list = GetListFromSomeWhere();
var list2 = GetListFromSomeWhere();
list.AddRange(list2);

....
...
var distinctedList = list.DistinctBy(x => x.ID).ToList();

More LINQat GitHub

More LINQGitHub

Or if you don't want to use external dlls for some reason, You can use this Distinctoverload:

或者,如果您出于某种原因不想使用外部 dll,则可以使用此Distinct重载:

public static IEnumerable<TSource> Distinct<TSource>(
    this IEnumerable<TSource> source, IEqualityComparer<TSource> comparer)

Usage:

用法:

public class FooComparer : IEqualityComparer<Foo>
{
    // Products are equal if their names and product numbers are equal.
    public bool Equals(Foo x, Foo y)
    {

        //Check whether the compared objects reference the same data.
        if (Object.ReferenceEquals(x, y)) return true;

        //Check whether any of the compared objects is null.
        if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
            return false;

        return x.ID == y.ID
    }
}



list.Distinct(new FooComparer());

回答by JScott

Not sure if anyone is still looking for any additional ways to do this. But I've used this code to remove duplicates from a list of User objects based on matching ID numbers.

不确定是否有人仍在寻找任何其他方法来做到这一点。但是我已经使用此代码根据匹配的 ID 号从用户对象列表中删除重复项。

    private ArrayList RemoveSearchDuplicates(ArrayList SearchResults)
    {
        ArrayList TempList = new ArrayList();

        foreach (User u1 in SearchResults)
        {
            bool duplicatefound = false;
            foreach (User u2 in TempList)
                if (u1.ID == u2.ID)
                    duplicatefound = true;

            if (!duplicatefound)
                TempList.Add(u1);
        }
        return TempList;
    }

Call: SearchResults = RemoveSearchDuplicates(SearchResults);

调用: SearchResults = RemoveSearchDuplicates(SearchResults);