Showing posts with label OrderBy. Show all posts
Showing posts with label OrderBy. Show all posts

Sunday, 17 June 2018

Sort Dictionary Based on Value in C#

As we already know that Dictionary works based on Key, Value pair. It provides us great flexibility to deal with lists or nested lists. Sorting a dictionary based on key is very easy but how would we sort it based on its value, I have designed a sample for a hint for you guys to help you with it.

Dictionary<string, int> Dict = new Dictionary<string, int>();
Dict.Add("James", 1);
Dict.Add("Lisa", 4);
Dict.Add("Ann", 2);
Dict.Add("Rick", 3);
var sortedDict = from x in Dict orderby x.Value ascending select x;

Output


You can also apply other options on other datatypes like StartsWith, Contains etc...

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"