user2017793
user2017793

Reputation: 55

Taking Distinct Column along with other column values also from DataTable in C#

I have a DataTable in which 4 cols are there. Col1, Col2, Col3, Col4. I want to filter the DataTable to take distinct Col1 values only.

DataView dv = MyDataSet.Tables[0].DefaultView;
listview.ItemsSource = dv.ToTable(true, new string[] { "Col1" }).DefaultView;

when i did this, listview shows only Col1 values but other columns are not showing.

But I cannot do like this,

dv.ToTable(true, new string[] { "Col1", "Col2", "Col3", "Col4" }).DefaultView;

Because i dont want other columns distinct values. More over the Col1 data is duplicating.

Is there any way to do it ? I want to do the filter in MyDataSet.Tables[0] only. Dont want to create another table to store the filter data as I am binding it to a WPF listview.

Upvotes: 0

Views: 646

Answers (1)

Thomas Levesque
Thomas Levesque

Reputation: 292455

You need to group by Col1, then take the first row of each group. The easiest way to do it is to use Linq to DataSets:

var query =
    from row in MyDataSet.Tables[0].AsEnumerable()
    group row by row.Field<int>("Col1") into g
    select g.First();

listview.ItemsSource = query.AsDataView();

(replace int with the actual data type of Col1)

Upvotes: 1

Related Questions