Click here to Skip to main content
15,792,870 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:

There are the following methods to sort a collection of List<t>
1-Using delegate
2-Using lambda expressions
3-Using IComparer
4-Implementing IComparable in the T class

Is there any benefits as to which of the above 4 techniques should be used, is there any performance associated.
I know it is better maintainable and read if we implement IComparable in our class and if he have multiple sorting criteria we can have IComparer.

Thanks everyone for your views.



1 and 2 are not comparable to 3 and 4
and besides - the performance of such functions will be determined mostly by the sorting algorithm itself, regardless of the implementation, this is one of the basic concepts of Computer Science

regarding delegate and lambda expressions, give us your usage and then we can relate to analyzing the performance of that example.
3. and 4. - and as a thumb rule: A well written code will (most of the times) top the performance of a off-the-shelf implementation.
However, then you have maintenance and upgrading to think of...

Good Luck,
Share this answer
I believe the sorting is implemented in the Sort internally by Miscrosoft.

We just provide the comparison rule
Consider the case

public class Employee
  public string Name{get;set;}
  public string Age{get;set;}
//Consider the list
//Say we populated the list with Employees
List<employee> employees = new List<employee>();
//1-Using Delegate
employees.Sort(delegate(Employee e1, Employee e2) { return e1.age.CompareTo(e2.age); });
//2-Using Lambda
employees.Sort((e1, e2) => e1.age.CompareTo(e2.age));
//3-Implement Icomparable in Employee class and write the same logic in Employee class //method CompareTo. Then we can call employees.Sort()
//4-Same for Icomparer as in comment 3

So I believe the sorting algo is written deep down in the .NET internals(as far as I know it implements a stable QuickSort algo), what we are providing is the sorting criteria.

My question is can we use any of the above 4 or is there a good, better and best in them

So when you are saying about the sorting algoritm there I can see I have little scope to do anything.
Thanks Edo for your reply and time.

Share this answer
Matt T Heffron 20-Feb-13 12:50pm    
It shouldn't be hard to write a simple program to try the variuos options and see for yourself!
You can probably do it more quickly than waiting for an answer here...

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900