Arooran
Arooran

Reputation: 637

Select distinct in Linq query

I've a collection with the data like this.

-------------------------------------------- 
|  key   | customer Name | code | isActive | 
--------------------------------------------
| 30002  |    XYZ        | 234  |     1    |
--------------------------------------------
| 30002  |    XYZ        | 234  |     1    |
--------------------------------------------
| 30002  |    XYZ        | 234  |     1    |
--------------------------------------------
| 30034  |    ERR        | 344  |     1    |
--------------------------------------------
| 30031  |    LDD        | 343  |     1    |
--------------------------------------------

how can select the distinct data using linq?

Upvotes: 1

Views: 6299

Answers (2)

Alex Dn
Alex Dn

Reputation: 5553

You can create your own comparier like this:

public class MyComparer : IEqualityComparer<DataRow>
    {
        public bool Equals(DataRow x, DataRow y) {
            return x["col1"] == y.["col1"] && x["col2"] == y.["col2"];
        }

        public int GetHashCode(DataRow obj) {
            return obj["col1"].GetHashCode() ^ obj["col2"].GetHashCode();
        }
    }

Then use:

var distinctRows = (from dr in table.AsEnumerable()
select dr).Distinct(new MyComparer());

I think that code can be optimized, but the overall idea is presented :)

Upvotes: 5

EgorBo
EgorBo

Reputation: 6142

captain obvious said that you should use Distinct linq method :-)

Upvotes: 6

Related Questions