Using Distinct with LINQ and Objects

后端 未结 5 1414
余生分开走
余生分开走 2021-01-03 23:20

Until recently, I was using a Distinct in LINQ to select a distinct category (an enum) from a table. This was working fine.

I now need to have it distinct on a class

5条回答
  •  無奈伤痛
    2021-01-03 23:21

    try an IQualityComparer

    public class MyObjEqualityComparer : IEqualityComparer
    {
        public bool Equals(MyObj x, MyObj y)
        {
            return x.Category.Equals(y.Category) &&
                   x.Country.Equals(y.Country);
        }
    
        public int GetHashCode(MyObj obj)
        {
            return obj.GetHashCode();
        }
    }
    

    then use here

    var comparer = new MyObjEqualityComparer();
    myObjs.Where(m => m.SomeProperty == "whatever").Distinct(comparer);
    

提交回复
热议问题