Select distinct only selects single column

Farshid picture Farshid · Nov 27, 2012 · Viewed 11.9k times · Source

Based on this question:

[How can I do SELECT UNIQUE with LINQ?

I wrote the below expression to select rows with unique OrganizationID column from the dt datatabe which contains multiple columns.

var distinctRows = (from DataRow dRow in dt.Rows
                    select new { col1 = dRow["OrganizationID_int"] }).Distinct();

but when I check distinctRows after the expression being executed, it only has records with 1 column (col1) instead of holding the whole columns. I afraid that adding expressions like col2=... and etc, may be interpreted that I want select distinct on all these columns.

So how can I get the whole row while applying unique filter on only 1 column but not the whole columns?

Answer

Tim Schmelter picture Tim Schmelter · Nov 27, 2012

I want the whole rows which satisfy that unique condition with all columns. I want to iterate in the next step.

So you don't want to group by that field and return one of the multiple rows. You want only rows which are unique.

One way is using Enumerable.GroupBy and count the rows in each group:

var uniqueRows = dt.AsEnumerable()
                   .GroupBy(r => r.Field<int>("OrganizationID_int"))
                   .Where(g => g.Count() == 1)
                   .Select(g => g.First());