4

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

Nomi Ali
  • 2,165
  • 3
  • 27
  • 48
  • 1
    Can't reproduce your problem. Are you sure that you are passing the right table to the GetDistinctRecords? – Steve Apr 09 '13 at 10:11
  • 1
    possible duplicate of [How to select distinct rows in a datatable and store into an array.](http://stackoverflow.com/questions/1199176/how-to-select-distinct-rows-in-a-datatable-and-store-into-an-array) – JNF Nov 23 '14 at 06:59

2 Answers2

13

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

Community
  • 1
  • 1
शेखर
  • 17,412
  • 13
  • 61
  • 117
6

Can you try this?

var myResult = dt.AsEnumerable().Select(c => (DataRow)c["MyColumn"]).Distinct().ToList();
Xelom
  • 1,615
  • 1
  • 13
  • 23