Search code examples
c#linqdatatablelinq-to-dataset

Get distinct column values in a set of datarows - Data Table Linq C#


I have a simple datatable with four columns and some datarows:

DataTable results = new DataTable();
results.Columns.Add("Wellbore", typeof(string));
results.Columns.Add("Date", typeof(DateTime));
results.Columns.Add("WB", typeof(string));
results.Columns.Add("factor", typeof(double));

I used Linq query to get "list of data rows" when "date=1/1/2017" as:

var AllRowsAtPlanningDate = results.AsEnumerable()
   .Where(x => ((x.Field<DateTime>("Date") == PlanningDate))).ToList();

I would like to get "distinct" values in the "wellbore" column in AllRowsAtPlanningDate . I just want the List<string> and not list<datarows> again.

How to do that? I have been checking some examples here but to no avail.


Solution

  • var AllRowsAtPlanningDate = results.AsEnumerable()
             .Where(r => r.Field<DateTime>("Date") == PlanningDate) // filter rows by date
             .Select(r => r.Field<string>("Wellbore")) // select only wellbore string value
             .Distinct() // take only unique items
             .ToList();