I have a DataTable with 22 columns and one of the columns I have is called "id". I would like to query this column and keep all the distinct values in a list. The table can have between 10 and a million rows.
What is the best method to do this? Currently I am using a for loop to go though the column and compare the values and if the values are the same then the it goes to the next and when not the same it adds the id to the array. But as the table can have 10 to a million rows is there a more efficient way to do this! How would I go about doing this more efficiently?
dt
- your data table nameColumnName
- your columnname i.e idSorry to post answer for very old thread. my answer may help other in future.
Try this:
Method 1:
Method 2: You will have to create a class matching your datatable column names and then you can use the following extension method to convert Datatable to List
and then you can get distinct from list using
Please note that this will return you complete Records and not just ids.
This will retrun you distinct Ids
All credit to Rajeev Kumar's answer, but I received a list of anonymous type that evaluated to string, which was not as easy to iterate over. Updating the code as below helped to return a List that was more easy to manipulate (or, for example, drop straight into a foreach block).