LINQ and DISTINCT using IEqualityComparer

Lagi kurang kerjaan nich ....  :P tapi bukan berarti minta boss(Buat bos gue kalo baca artikel ini)

 

this case is from Jimmy's blog

it raise a question  in my mind because i've used distinct in one column ,it works but when used on multiple column it doesn't

First of all disctinct is a set, so you can't use Lambda here, and only have to overload, whether nothing or iequalitycomparer.

 

Because of behind the hood disctinct use GetHashCode. http://blog.jordanterrell.com/post/LINQ-Distinct()-does-not-work-as-expected.aspx

So you Have to Define your own GetHashCode , this is all main key here. else it won't work

Now from the link of msdnlocal use the XOR.

 

because if you use iequalitycomparer will not work if the hashcode doesnot return unique combination of those fields.

Now what i want to add is using iequality, same result as jimmy.

the comparer

   1:   public class DistinctNameBirtDay : IEqualityComparer<Person>
   2:          {
   3:              public bool Equals(Person x, Person y)
   4:              {
   5:                  return x.Name.Equals(y.Name) && x.BirthDate.Equals(y.BirthDate);
   6:              }
   7:   
   8:              public int GetHashCode(Person obj)
   9:              {
  10:                  return obj.Name.GetHashCode() ^ obj.BirthDate.GetHashCode(); ;
  11:              }
  12:          }
 
the main and distinct
   1:   static void Main(string[] args)
   2:          {
   3:              var people = new[] {
   4:   
   5:                  new Person("Unyil", DateTime.Today),
   6:   
   7:                  new Person("Cuplis", DateTime.Today.AddDays(1)),
   8:   
   9:                  new Person("Ucok", DateTime.Today.AddDays(2)),
  10:   
  11:                  new Person("Unyil", DateTime.Today),
  12:   
  13:                  new Person("Cuplis", DateTime.Today.AddDays(1)),
  14:   
  15:                  new Person("Pak Raden", DateTime.Today.AddDays(-5))
  16:   
  17:              };
  18:   
  19:   
  20:              

             var query = people.Distinct(new DistinctNameBirtDay());

  21:             // var query = people.Distinct();
  22:   
  23:              
  24:   
  25:              foreach(var o in query)
  26:   
  27:              {
  28:   
  29:                  Console.WriteLine(o.ToString());
  30:   
  31:              }
  32:              Console.ReadLine();
  33:   
  34:          }
  35:      }
Share this post: | | | |
Published Thursday, November 06, 2008 3:25 PM by cipto
Filed under:

Comments

# http://blog.jordanterrell.com/post/linq-distinct()-does-not-work-as-expected.aspx

Friday, February 27, 2009 2:55 PM by TrackBack

# acai berries

Tuesday, June 09, 2009 11:00 PM by acai berries

La figure humaine, apr s avoir disloqu en cinquante ans...