Skip to content
May 24, 2010 / kiranpatils

Generic List Sorting

Generic List has powerful sorting method which too less .Netters are aware of. Today, I would like to show it’s power to you guys!

Here we go..

Suppose, you have a Class called Employee and created collection of employees using Generic List as shown below:

 public class Employee
 {
 public int EmployeeID { get; set; }
 public string EmployeeName { get; set; }
 public Employee(int employeeId, string employeeName)
 {
 EmployeeID = employeeId;
 EmployeeName = employeeName;
 }

 public override string ToString()
 {
 return EmployeeID + " :- " + EmployeeName;
 }
 }

List<Employee> employeeList = new List<Employee>();
employeeList.Add(new Employee(2, "Sachin T"));
employeeList.Add(new Employee(1, "Anil K"));

Now, if you need to sort your employees collection by EmployeeID how will you do it? – I know i know you will write your logic and do so many things..But hold on how it will be if we can do it in just one line? sounds cool na? Here you go:

Console.WriteLine(">>>>>>>>>>Before Sorting<<<<<<<<<<");
 foreach (Employee employee in employeeList)
 {
 Console.WriteLine(employee.ToString());
 }

 // Sorting – Anonymous method
 employeeList.Sort(delegate(Employee employee1, Employee employee2)
 { return employee1.EmployeeID.CompareTo(employee2.EmployeeID); });

 Console.WriteLine(">>>>>>>>>>After Sorting<<<<<<<<<<");
 foreach (Employee employee in employeeList)
 {
 Console.WriteLine(employee.ToString());
 }

/* Output
 >>>>>>>>>>Before Sorting<<<<<<<<<<
 2 :- Sachin T
 1 :- Anil K
 >>>>>>>>>>After Sorting<<<<<<<<<<
 1 :- Anil K
 2 :- Sachin T
 Press any key to continue . . .
 */

Links

http://weblogs.asp.net/dwahlin/archive/2007/04/23/The-Power-of-Anonymous-Methods-in-C_2300_.aspx

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: