Distinct list of objects based on an arbitrary key in LINQ

前端 未结 5 1404
鱼传尺愫
鱼传尺愫 2020-12-05 05:43

I have some objects:

class Foo {
    public Guid id;
    public string description;
}

var list = new List();
list.Add(new Foo() { id = Guid.Empt         


        
5条回答
  •  暖寄归人
    2020-12-05 06:14

    Using the Distinct() method is about 4x faster than using GroupBy() in my informal tests. For 1 million Foo's my test has Distinct() at about 0.89 seconds to make a unique array out of a non-unique array where GroupBy() takes about 3.4 seconds.

    My Distinct() call looks like,

    var unique = list.Distinct(FooComparer.Instance).ToArray();
    

    and FooComparer looks like,

    class FooComparer : IEqualityComparer {
        public static readonly FooComparer Instance = new FooComparer();
    
        public bool Equals(Foo x, Foo y) {
            return x.id.Equals(y.id);
        }
    
        public int GetHashCode(Foo obj) {
            return obj.id.GetHashCode();
        }
    }
    

    and my GroupBy() version looks like,

    var unique = (from l in list group l by l.id into g select g.First()).ToArray();
    

提交回复
热议问题