C# Linq intersect/except with one part of object

后端 未结 7 976
终归单人心
终归单人心 2020-11-29 07:16

I\'ve got a class:

class ThisClass
{
  private string a {get; set;}
  private string b {get; set;}
}

I would like to use the Intersect and

相关标签:
7条回答
  • 2020-11-29 08:12

    If you want a list of a single property you'd like to intersect then all the other pretty LINQ solutions work just fine. BUT! If you'd like to intersect on a whole class though and as a result have a List<ThisClass> instead of List<string> you'll have to write your own equality comparer.

    foo.Intersect(bar, new YourEqualityComparer());
    

    same with Except.

    public class YourEqualityComparer: IEqualityComparer<ThisClass>
    {
    
        #region IEqualityComparer<ThisClass> Members
    
    
        public bool Equals(ThisClass x, ThisClass y)
        {
            //no null check here, you might want to do that, or correct that to compare just one part of your object
            return x.a == y.a && x.b == y.b;
        }
    
    
        public int GetHashCode(ThisClass obj)
        {
            unchecked
            {
                var hash = 17;
                                //same here, if you only want to get a hashcode on a, remove the line with b
                hash = hash * 23 + obj.a.GetHashCode();
                hash = hash * 23 + obj.b.GetHashCode();
    
                return hash;    
            }
        }
    
        #endregion
    }
    
    0 讨论(0)
提交回复
热议问题