0

I want to use the distinct clause for multiple levels. Firstly i tried with DataTable but did't got success so i converted DataTable to AsEnumerable.

My problem here is that the Fields which i have specified/hard coded will be coming dynamic, same for both Where & Select.

How to add dynamic Fields in Where & Select?

DataTable data3 = new DataTable();
var listData = data3.AsEnumerable()
               .Where(m => !String.IsNullOrEmpty(m.Field<string>("clientname"))
               && !String.IsNullOrEmpty(m.Field<string>("project"))
               && !String.IsNullOrEmpty(m.Field<string>("postedstate"))
               && !String.IsNullOrEmpty(m.Field<string>("postedcity"))
               && !String.IsNullOrEmpty(m.Field<string>("siteadd")))
               .Select(row => new
                {
                   clientname = row.Field<string>("clientname"),
                   project = row.Field<string>("project"),
                   postedstate = row.Field<string>("postedstate"),
                   postedcity = row.Field<string>("postedcity"),
                   siteadd = row.Field<string>("siteadd")
                }).Distinct();
Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236
Anup
  • 9,396
  • 16
  • 74
  • 138
  • Why they come dynamic? In what way they are dynamic? Can you show how they are passed? – Tim Schmelter Sep 03 '18 at 10:52
  • 1
    You are *already* using field names dynamically. You *can* return distinct rows from a DataTable, as shown [here](https://stackoverflow.com/questions/1199176/how-to-select-distinct-rows-in-a-datatable-and-store-into-an-array). What did you try and what didn't work? – Panagiotis Kanavos Sep 03 '18 at 10:55
  • 2
    Are you confusing the terminology of the, `dynamic` type, and an anonymous type? – TheGeneral Sep 03 '18 at 10:55
  • Possible duplicate of [How to select distinct rows in a datatable and store into an array](https://stackoverflow.com/questions/1199176/how-to-select-distinct-rows-in-a-datatable-and-store-into-an-array) – Panagiotis Kanavos Sep 03 '18 at 10:56

1 Answers1

0

You could do something similar to this:

string clientName = "my client";
string project = null;

DataTable data3 = new DataTable();
var listData = data3.AsEnumerable().Where(m => 
    (String.IsNullOrEmpty(clientName) || m.Field<string>("clientname") == clientName)
    && (String.IsNullOrEmpty(project) || m.Field<string>("project") == project)
).Select(row => new Project()
{
    clientname = row.Field<string>("clientname"),
    project = row.Field<string>("project"),
    postedstate = row.Field<string>("postedstate"),
    postedcity = row.Field<string>("postedcity"),
    siteadd = row.Field<string>("siteadd")
}).Distinct();

This way you will have no need to have an anonymous type returned and get rid of the problem.

Cleptus
  • 3,446
  • 4
  • 28
  • 34