Friday, December 7, 2007

Sorting Generic List in C#

You can sort a generic List in C# using different methods. Here I cover only two options which I found them most handy. The third option is to put the method into a class that implements the IComparer interface.




using System;
using System.Collections.Generic;

public class SortingList
{
/// <summary>
/// SortingList: This snippet code demonstrates the delegate method of sorting lists
/// I define an Item type having some fields and sort based on a preferred field
/// To do so I need to implement a method would be called during the sort action for each pair.
///
/// NOTE: You could also create a class implementing IComparer and use the class to pass to the Sort method.
///
/// Asghar Panahy
/// 07-12-2007
/// </summary>
public static void Main()
{
List
<Item> list = new List<Item>();

// Adding some dummy items
list.Add(new Item("6", " Asghar 1"));
list.Add(
new Item("5", " Asghar 2"));
list.Add(
new Item("3", " Asghar 3"));
list.Add(
new Item("4", " Asghar 4"));
list.Add(
new Item("2", " Asghar 5"));
list.Add(
new Item("1", " Asghar 6"));

Console.WriteLine(
"Dumping the list:");
DumpList(list);

// Sorting it by ID
list.Sort(SortByID);

Console.WriteLine(
"Dumping the list:");
DumpList(list);

// Second Option, using anonimous methods
// Sorting it by Birthday
list.Sort(
delegate (Item i1, Item i2)
{
return i1.Birthday.CompareTo(i2.Birthday);
}
);

Console.WriteLine(
"Dumping the list:");
DumpList(list);

// Wait for response before closing it
Console.ReadLine();

}
public static int SortByID(Item s1, Item s2)
{
return s1.ID.CompareTo(s2.ID);
}

public static void DumpList(List<Item> list)
{
foreach(Item l in list)
{
Console.WriteLine(l);
}
}

}

// Sample Class
public class Item
{
public Item(string id, string name)
{
this.ID = id;
this.Name = name;
this.Birthday = DateTime.Now;
}
public string Name;
public string ID;
public DateTime Birthday;
public override string ToString()
{
return String.Format("{0} is born on {1}", this.Name, this.Birthday.ToLocalTime());
}
}
}



4 comments:

Peter Cooke said...

Great examples exactly what I was looking for!

Alakmalak Technologies said...

Hi, its a nice post it tells us about c#, You may have noticed that a Skip List is sort of like a LinkedList. That is exactly correct, skip lists in a series of LinkedLists stacked on top of each other. If you don' t know what a LinkedList is, don't worry about it.
Thanks for this nice sharing.

husle

Alakmalak Technologies said...
This comment has been removed by the author.
Manohar said...

Hi,

Your post was very worthful. Please keep posting. helps an n mumber of people like me. Thank you very much