开发者

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 u开发者_C百科nique rows based on these three values:

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

How can this be done most easily using linq?


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());


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

class MyComparer : IEqualityComparer<YourRowClass>

then use it like

yourList.Distinct(MyComparer())
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜