Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Distinct records in DataTable

I want to get distinct records based on some fields. I'm using the following method:

string[] TobeDistinct = { "PKID" };
DataTable dtDistinct = GetDistinctRecords(ds.Tables[0], TobeDistinct);
DataSet ds2 = new System.Data.DataSet();
ds2.Tables.Add(dtDistinct);

public static DataTable GetDistinctRecords(DataTable dt, string[] Columns)
{
    DataTable dtUniqRecords = new DataTable();
    dtUniqRecords = dt.DefaultView.ToTable(true, Columns);
    return dtUniqRecords;
}

This gives me the distinct records, but only two records come. Only two distinct PKID will come. For example, I have multiple records with PKID 10,12,14,16, but the result is 2 rows with PKID 10 and 12. More two rows are not there, but should be there. What do I need to do?

I follow this article: http://www.codeproject.com/Tips/153008/Select-DISTINCT-records-based-on-specified-fields

enter image description here

like image 959
Nomi Ali Avatar asked Nov 30 '22 21:11

Nomi Ali


2 Answers

You can use like follows

DataView view = new DataView(table);
DataTable distinctValues = view.ToTable(true, "Column1", "Column2" ...);

More detail
How to select distinct rows in a datatable and store into an array

like image 88
शेखर Avatar answered Dec 05 '22 15:12

शेखर


Can you try this?

var myResult = dt.AsEnumerable().Select(c => (DataRow)c["MyColumn"]).Distinct().ToList();
like image 34
Xelom Avatar answered Dec 05 '22 15:12

Xelom