Recommended hosting
Sep 26 2006

Collections part 3 - basic sorting with IComparer

Posted by admin under .NET

Please read this article serie from the beginning

Now lets sort our collection. Lets incapsulate it by adding a Sort function to our LinkCollection:



	public class LinkColl : CollectionBase	
	{
		public void Sort()
		{
			InnerList.Sort(new LinkComparer());
		}
...
...


As you can see we call the InnerList.Sort function - passing in a LinkComparer object. Now - lets look at the LinkComparer:



	public class LinkComparer : IComparer	
	{
		#region IComparer Members

		public int Compare(object x, object y)
		{
			Link oLink1 = x as Link;
			Link oLink2 = y as Link;
			return oLink1.Name.CompareTo(oLink2.Name);
		}

		#endregion
	}


As you can see it implements the interface IComparer. Thanks to that  the function InnerList.Sort will be able to do all the sorting for us - it will simply call our LinkComparer object whenever it needs to compare two objects. So all we need to do is compare two objects sent in to the function (they will be Link objects - the collection can only contain Link objects, remember? ). So it's safe to typecast the object parameters to Link objects and do our sorting - I have chosen to just compare the name.

 So - our GUI code can just look like this:



			oColl.Sort();
			foreach( Link oLink in oColl )
			{
				Console.WriteLine( oLink.Name + ":" + oLink.Url );
			}

Download is available in part 4