Thursday 28 July 2011

Sorting a list of object in c sharp

There are three methods to sort list of  objects in c sharp. one is using Deletages, second Implementing IComparer interface, and other one is using linq to objects

Implementing IComparer(C#1.0)
class ContactNameComparer : IComparer
{
public int Compare(Contact x, Contact y)
{
return x.Name.CompareTo(y.Name);
}
}
...
List<Contact> contacts=Contact.SampleData();
contacts.Sort(new ContactNameComparer());
foreach (Contact contact in contacts)
{
Console.WriteLine(contact);
}


Using  inline delegates(from C#2.0)

List<Contact> contacts = Contact.SampleData();
// sort by last name
contacts.Sort(
delegate(Contact c1, Contact c2)
{
if (c1 != null && c2 != null)
return string.Compare(
c1.LastName, c2.LastName);
return 0;
}
);

Using Linq to Objects(From C#3.0)

List<Contact> contacts = Contact.SampleData();
// perform the LINQ query
var query = from c in contacts
orderby c.State, c.LastName;

No comments:

Post a Comment