Sep 26 2006

Collection part 4 - multiple fields sorting, asc desc order

Posted by admin under .NET

This is part 4 of this article serie on collections in C# - please start by reading Part 1  

Our basic sorting is simply just too basic. Lets add the possibility to sort on multiple fields - and also to sort in ascending or descending order.

First lets add some stuff to our LinkComparer: 



	public class LinkComparer : IComparer	
	{
		public enum SortingFields
		{
			Name,
			Url
		}
		public enum SortAscDesc
		{
			Asc,
			Desc
		}
		private SortingFields m_SortField;
		private SortAscDesc m_AscDesc;


		public LinkComparer(SortingFields sortField, SortAscDesc ascDesc)
		{
			m_SortField = sortField;
			m_AscDesc = ascDesc;
		}

		#region IComparer Members

		public int Compare(object x, object y)
		{
			Link oLink1 = x as Link;
			Link oLink2 = y as Link;
			int nRet = 0;
			if ( m_SortField == SortingFields.Name )
				nRet = oLink1.Name.CompareTo(oLink2.Name);
			else if ( m_SortField == SortingFields.Url )
				nRet = oLink1.Url.CompareTo(oLink2.Url);
			if ( m_AscDesc == SortAscDesc.Desc )
				nRet = -nRet;
			return nRet;
		}

		#endregion
	}


First we have added two enums. SortingFields is whiich field to sort on and SortAscDesc is the sort order.

We have also modified the LinkComparer constructor. Now it takes a variable each of the two enum types - and we store the values in private variables.

Now in Compare we just check to see which field to compare - is it SortingFields.Name? fine - lets do a compare on Name. Is it SortingFields.Url - fine lets compare the Url property.

Last a cool trick: if we have specified descending order (m_AscDesc == SortAscDesc.Desc) we just invert the returned value from CompareTo.

And we change the LinkCollection accordingly:



	public class LinkColl : CollectionBase	
	{
		public void Sort( LinkComparer.SortingFields sortField, LinkComparer.SortAscDesc ascDesc   )
		{
			InnerList.Sort(new LinkComparer(sortField, ascDesc));
		}



and now the calling GUi classes can select which sorting parameters they want to sort on (and all in a typesafe manner):



			oColl.Sort( LinkComparer.SortingFields.Name, LinkComparer.SortAscDesc.Desc );
			foreach( Link oLink in oColl )
			{
				Console.WriteLine( oLink.Name + ":" + oLink.Url );
			}



Please download the attached file. The example is a command line C# application.

Attachments