Remove objects with a duplicate property from List

后端 未结 4 567
陌清茗
陌清茗 2021-02-04 23:03

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.

How can I trim the List (or make a

4条回答
  •  爱一瞬间的悲伤
    2021-02-04 23:56

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

    More LINQ at GitHub

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

    public static IEnumerable Distinct(
        this IEnumerable source, IEqualityComparer comparer)
    

    Usage:

    public class FooComparer : IEqualityComparer
    {
        // 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());
    

提交回复
热议问题