KnowDotNet NetRefactor

Pass delegate as Anonymous Method in C# To Sort List of Objects

Using the Sort Method of a Generic List

by Les Smith
Print this Article Discuss in Forums

How can I sort a List of generic objects?  Use a delegate and the default Sort method of the List Object.  Let's say that I have a Business Object that has as one of its properties a List<T>.  I can sort this List of objects using the Sort method of the List Object if I pass it a delegate, as an anonymous method, telling it how to sort the List.  The one line of code that it takes to do this in C# is shown below.  

  pn.StatusHistory.Sort(delegate(UserPhoneNumberHistory h1,
    
UserPhoneNumberHistory h2)
    {
return h2.HistoryDateTime.CompareTo(h1.HistoryDateTime); });

In this instance, I want the
UserPhoneNumberHistory objects sorted in descending order on the HistoryDateTime field.  If I reversed the parameters to the delegate method, the objects would be sorted in ascending order by date and time.

I currently develop mostly in C#, but used VB.NET for years and still do occasionally.  I am always interested in new ways, especially shortcuts, of accomplishing a task.  I don't think you can do the above in VB.NET, at least with one line of code.  However, I was trying to make a ComClass this week to be called from classic VB5 (don't ask why) and found that VB.NET has a ComClass template that automatically creates a class that is callable as Com, but in C# a little more work is involved because C# does not have this kind of a template.  I guess I keep the "flame war" going in my mind:)  Just kidding, I like both languages, much to the chagrin of my current manager.

Need to automatically organize your code windows?  You'll be amazed how easy it is to keep the code in your code windows organized.  TRY IT FREE FOR 30 DAYS BY CLICKING HERE.



Automatically generate braces in C#! Try CSharpCompleter and stop wasting valuable time needlessly typing hundreds of braces {} daily.  Try CSharpCompleter for 30 DAYS FREE.



Ask a Question, or give your feedback on my articles or products by going to the KnowDotNet Forum or by clicking on My Blog.
  

You can also email me directly at les@KnowDotNet.com.



Writing Add-Ins for Visual Studio .NET
Writing Add-ins for Visual Studio .NET
by Les Smith
Apress Publishing