C# Linq intersect/except with one part of object

后端 未结 7 975
终归单人心
终归单人心 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 07:52

    Not sure of the speed of this compared to intersect and compare but how about:

    //Intersect
    var inter = foo.Where(f => bar.Any(b => b.a == f.a));
    //Except - values of foo not in bar
    var except = foo.Where(f => !bar.Any(b => b.a == f.a));
    
    0 讨论(0)
  • 2020-11-29 07:55

    I know this is old but couldn't you also just override the Equals & GetHashCode on the class itself?

    class ThisClass
    {
      public string a {get; set;}
      private string b {get; set;}
    
      public override bool Equals(object obj)
      {
        // If you only want to compare on a
        ThisClass that = (ThisClass)obj;
        return string.Equals(a, that.a/* optional: not case sensitive? */);
      }
    
      public override int GetHashCode()
      {
        return a.GetHashCode();
      }
    }
    
    0 讨论(0)
  • 2020-11-29 07:58

    Maybe

    // returns list of intersecting property 'a' values
    foo.Select(f => f.a).Intersect(bar.Select(b => b.a));
    

    BTW property a should be public.

    0 讨论(0)
  • 2020-11-29 07:58

    You should create IEqualityComparer. You can pass the IEqualityComparer to Intersect() method. This will help you get List(which intersect with bar) easier.

    var intersectionList = foo.Intersect(bar, new ThisClassEqualityComparer()).ToList();
    
    
    class ThisClassEqualityComparer : IEqualityComparer<ThisClass>
    {
    
        public bool Equals(ThisClass b1, ThisClass b2)
        {
            return b1.a == b2.a;
        }
    
    
        public int GetHashCode(Box bx)
        {
           // To ignore to compare hashcode, please consider this.
           // I would like to force Equals() to be called
           return 0;
        }
    
    }
    
    0 讨论(0)
  • 2020-11-29 07:59

    What exactly is the desired effect? Do you want to get a list of strings composed of all the a's in your classes, or a list of ThisClass, when two ThisClass instances are identified via unique values of a?

    If it's the former, the two answers from @lazyberezovksy and @Tilak should work. If it's the latter, you'll have to override IEqualityComparer<ThisClass> or IEquatable<ThisClass> so that Intersect knows what makes two instances of ThisClass equivalent:

     private class ThisClass : IEquatable<ThisClass>
     {
         private string a;
    
         public bool Equals(ThisClass other)
         {
            return string.Equals(this.a, other.a);
         }
     }
    

    then you can just call:

     var intersection = foo.Intersect(bar);     
    
    0 讨论(0)
  • 2020-11-29 08:07
    foo.Select(x=>x.a).Intersect(bar.Select(x=>x.a))
    
    0 讨论(0)
提交回复
热议问题