sooprise
sooprise

Reputation: 23187

Getting Unique Combinations Of Particular Table?

Table1:

ValueA
ValueB
ValueC

Example Data:

1,2,3
1,2,4
1,2,4
1,2,4
1,5,6
1,5,6

I want to get the unique rows based on these three values:

1,2,3
1,2,4
1,5,6

How can this be done most easily using linq?

Upvotes: 0

Views: 77

Answers (2)

jason
jason

Reputation: 241641

Write your own IEqualityComparer and use Enumerable.Distinct on a collection of your objects representing the rows.

Something like (sorry, did not test in a compiler):

class Foo {
    public int ValueA { get; set; }
    public int ValueB { get; set; }
    public int ValueC { get; set; }
}

class FooEqualityComparer : IEqualityComparer<Foo> {
   public bool Equals(Foo x, Foo y) {
       if(Object.ReferenceeEquals(x, y)) { return true; }
       if(x == null || y == null) { return false; }
       return x.ValueA == y.ValueA &&
              x.ValueB == y.ValueB &&
              x.ValueC == y.ValueC;
   }

   public int GetHashCode(Foo obj) {
       if(obj == null) { return 0; }
       unchecked {
           int hashCode = 17;
           hashCode = hashCode * 23 + obj.ValueA.GetHashCode();
           hashCode = hashCode * 23 + obj.ValueB.GetHashCode();
           hashCode = hashCode * 23 + obj.ValueC.GetHashCode();
           return hashCode;
       }
   }
}

Then:

IEnumerable<Foo> foos = // some foos;
var distinct = foos.Distinct(new FooEqualityComparer());

Upvotes: 1

ub1k
ub1k

Reputation: 1674

you could use .Distinct() with your own comparer class

class MyComparer : IEqualityComparer<YourRowClass>

then use it like

yourList.Distinct(MyComparer())

Upvotes: 0

Related Questions