Sunday, November 25, 2007

Sort a List of Generics using anonymous method

I bumped across a code in my project where they use anonymous method to do sorting which was pretty difficult to understand. So I decided to write my own piece of code to understand how this stuff works:
******************************************************************************
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
List dinosaurs = new List();

Console.WriteLine("\nCapacity: {0}", dinosaurs.Capacity);

dinosaurs.Add("Tyrannosaurus");
dinosaurs.Add("aAmargasaurus");
dinosaurs.Add("Mamenchisaurs");
dinosaurs.Add("Deinonychus");
dinosaurs.Add("Compsognathus");

Console.WriteLine("\nCapacity: {0}", dinosaurs.Capacity);
Console.WriteLine("Count: {0}", dinosaurs.Count);
foreach(string dinosaur in dinosaurs)
{
Console.WriteLine("dinosaur before Sort"+dinosaur);
}

dinosaurs.Sort(delegate(string r1, string r2)
{
if(r1.Length == r2.Length)
{
return r1.CompareTo(r2);
}
else{
return r1.Length.CompareTo(r2.Length);
}
});

foreach(string dinosaur in dinosaurs)
{
Console.WriteLine("dinosaur after Sort"+dinosaur);
}


}
}
}
******************************************************************************The most difficult portion to understand was
dinosaurs.Sort(delegate(string r1, string r2)
I really dint understand how r1 and r2 picks up the correct values. The issue is its so randomly picks up values and sometimes r1 == r2

No comments: