Distinct in linq?

前端 未结 5 1268
我寻月下人不归
我寻月下人不归 2020-12-31 20:07

I am wondering how can I achieve this?

I want to get only distinct names from a collection of objects

MyObject a = new Object();
a.Name = \'One\';
a.         


        
5条回答
  •  说谎
    说谎 (楼主)
    2020-12-31 20:24

    You can implement your class so the linq distinct operator does not use the default equality comparer.

    class YourClass:IEquatable 
    {
    

    ... Your implementation details. ...

        public bool Equals(YourClass other)
        {
            if (Object.Equals(this, other))
            {
                return true;
            }
            else
            {
                if(Name == other.Name && Value == other.Value)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }
    
     public override int GetHashCode()
     {
         return Name.GetHashCode() ^ Value.GetHashCode();
     }
    
    }
    

提交回复
热议问题