Monday, May 26, 2008

Sorting using C# generics

Using anonymous methods and generics can change the nature of coding as a whole and C# does a great job in providing the coveted flexibility to a developer.
Initially, it looks like a whole lot of paradigm shift but later it becomes a habit and more so, an addiction.

Here is an example that shows one of the shortest ways to sort a list of Persons according to any property desired.(Class: Person, List stands for the generic list which is having a type Person now).

Lets us enter some code.

//Class Person

public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public int Salary { get; set; }
public Person(string name, int age, int salary)
{
this.Name = name;
this.Age = age;
this.Salary = salary;
}
}

//Initializing a list of Persons
//This may not be static for this example.
//But we might have to make it static for a later example.

static List persons = new List();
public bool isEqual { get; set; }

persons.Add(new Person("chander", 26, 88000));
persons.Add(new Person("jiggi", 26, 80000));
persons.Add(new Person("puneet", 26, 90000));
persons.Add(new Person("chander", 26, 95000));
persons.Add(new Person("jiggi", 26, 10000));
persons.Add(new Person("chander", 26, 85000));
persons.Add(new Person("chander", 26, 1000000));
persons.Add(new Person("jiggi", 26, 34535));
persons.Add(new Person("chander", 26, 86000));

//Sorting according to a property of the class Person.
//It is just a matter of one line code.

persons.Sort(delegate(Person p1, Person p2) { return p1.Name.CompareTo(p2.Name); });

//The anonymous delegate sorts the list 'persons' according to the 'Name' property.
//Replacing 'Name' by other properties could easily make it sortable by that property.

//This could be now printed using a foreach statement

foreach (Person p in persons)
{
Console.Writeline("Name {0}, Salary {1}, Age {2}",p.Name, p.Salary, p.Age);
}
Console.Readkey();


//Comments
//The whole code is just trivia and it's only one line of code that makes it happen. YAY!!!

No comments: