I know web pages should be past this, but this site doesn't look right on IE.
I will fix it some day ( not for IE 6 though) but for now this is easier and a lot more fun.

Download firefox or chrome or hide this message forever...
<< Back to blog main

I have recently discovered delegates in C# and find them to be indispensable. Below are a few examples of using delegates with Lists. Lets start with a simple list of strings:

List<string> items = new List<string >(); items.Add("Brian"); items.Add("Peter"); items.Add("Lois"); items.Add("Meg"); items.Add("Chris"); items.Add("Stewie");
Now if you want to sort this list all you have to call

items.Sort();

and the list in the order: Brian, Chris, Lois, Meg, Peter, Stewie.
But what if you wanted to sort by the length of the string? That could get a little tricky; however, with delegates, it’s not bad at all:
items.Sort(delegate(string s1, string s2) { return s1.Length.CompareTo(s2.Length); }); and you get the list in the order: Meg, Lois, Peter, Brian, Chris, Stewie.

Lets look at some other application of delegatesa with Lists. Lets say you wanted to get all the strings in the list of a given length.

int length = 5; List<string> lengthOfFive = items.FindAll(delegate(string s) { return s.Length == length; });

and the list lengthOfFive contains Peter, Brian, Chris.

What if you need to do something for each object? You could use the a delegate with the ForEach function. This will print the total number of letters in List of strings:

int letters = 0; items.ForEach( delegate(string s) { letters += s.Length; }); Console.WriteLine("Total number of letters: " + letters);

and this will print all the strings in the list:

items.ForEach(delegate(string s) { Console.WriteLine(s ); });

We can get easily rid of Meg, because let’s face it, no one likes Meg.
items.RemoveAll(delegate(string s) { return s.Equals("Meg"); });

and now we have list that doesn’t have Meg in it.
When a List of strings is no longer good enough and we need a List of Person we can use the ConvertAll to help us out.
List<Person> people= items.ConvertAll<Person>(delegate(string s ){ return new Person(s); });