Sunday 17 June 2018

Using LINQ get distinct, ordered list from DataTable in C#

Sometimes we need to get distinct, sorted list of names from a DataTable using LINQ, It may be an employee list we need to perform operations on. We can do this by using LINQ in a simple way as mentioned below

// Create new Datatable with 3 columns
DataTable table = new DataTable();
table.Columns.Add("Name", typeof(string));
table.Columns.Add("Age", typeof(int));
table.Columns.Add("Salary", typeof(int));
 
//Add Data Rows.
table.Rows.Add("James", 29, 32000);
table.Rows.Add("Lisa", 25, 55000);
table.Rows.Add("Aron", 31, 42000);
table.Rows.Add("John", 26, 50000);
table.Rows.Add("Rick", 32, 125000);
table.Rows.Add("Lisa", 25, 55000);
 
//Enumerable Unique Sorted List of Employees using LINQ 
var SortedDistinctData = (from x in table.AsEnumerable()
     select (string)x["Name"]).Distinct().OrderBy(Name => Name);

You can see the output in the attached image

Image not shown
Fig
If you want to sort them based on their salary or age, just change their column name like replace "Name" to "Age" or "Salary"

No comments:

Post a Comment