Archive for the ‘LINQ’ category

Updated Multi-Property Sorting with LINQ

August 1, 2008

In the quest to bring you, the consumer, an ever increasingly useful product, I present the new and improved ListSorter class!

During a peer review, a fellow developer asked if he could use this code to continue sorting on a previously sorted list. The answer was of course, “Erm…” So I took a look at what I had and did some refactoring. The new code (shown below) is now implemented as extension methods to the IEnumerable and IOrderedEnumerable interfaces. The Sort method will perform a primary ordering on an IEnumerable, whereas ContinueSort will perform subsequent ordering on an already sorted collection. Sort will call ContinueSort if there is more than one sort option passed in.

I’m still looking for a good way to supply a collection of IComparer objects to the sorting methods such that these comparers can be applied either to specific properties or to all properties of a given type. I may be able to pass the comparers along as simple objects and cast them to the appropriate type once the property is found, or the type comes up, but that just seems extra messy. I’m interested to hear any ideas on this, and will post an update if a solution is found.

In the meantime, enjoy!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using System.Reflection;

namespace ESC.SV.UI.Win.RATA.Helpers
{
	public static class ListSorter
	{
		public enum SortingOrder
		{
			Ascending,
			Descending,
		};

		public static IOrderedEnumerable Sort(this IEnumerable toSort, IDictionary sortOptions)
		{
			IOrderedEnumerable orderedList = null;

			if (sortOptions != null && sortOptions.Count > 0)
			{
				//Create a copy of our dictionary to preserve the original.  We'll be removing items, so we don't want to mess up the reference.
				Dictionary sortCopy = sortOptions.Copy();

				//Get the primary sort option and remove it from the list
				//We will later check if there are additional elements in the list for further sorting
				KeyValuePair primarySort = sortCopy.ElementAt(0);
				sortCopy.Remove(primarySort.Key);

				orderedList = primarySort.Value == SortingOrder.Ascending ? toSort.ApplyOrder(primarySort.Key, "OrderBy") : toSort.ApplyOrder(primarySort.Key, "OrderByDescending");

				//Continue the sort if there are more options
				if (sortCopy.Count > 0)
				{
					orderedList = orderedList.ContinueSort(sortCopy);
				}
			}

			return orderedList;
		}

		public static IOrderedEnumerable ContinueSort(this IOrderedEnumerable orderedList, IDictionary sortOptions)
		{
			if (sortOptions != null)
			{
				foreach (KeyValuePair entry in sortOptions)
				{
					orderedList = entry.Value == SortingOrder.Ascending ? orderedList.ApplyOrder(entry.Key, "ThenBy") : orderedList.ApplyOrder(entry.Key, "ThenByDescending");
				}
			}

			return orderedList;
		}

		private static IOrderedEnumerable ApplyOrder(this IEnumerable source, string property, string methodName)
		{
			ParameterExpression param = Expression.Parameter(typeof(T), "x");
			Expression expr = param;

			//Create the right-hand part of the lambda expression based on the property provided
			foreach (string prop in property.Split('.'))
			{
				expr = Expression.PropertyOrField(expr, prop);
			}

			Type delegateType = typeof(Func).MakeGenericType(typeof(T), expr.Type);
			LambdaExpression lambda = Expression.Lambda(delegateType, expr, param);

			//Fetch the desired method
			MethodInfo mi = typeof(Enumerable).GetMethods().Single(method =>
				method.Name == methodName
				&& method.IsGenericMethodDefinition
				&& method.GetGenericArguments().Length == 2	// 
				&& method.GetParameters().Length == 2)		// source, keySelector
				.MakeGenericMethod(typeof(T), expr.Type);	// Substitute the appropriate types

			return (IOrderedEnumerable)mi.Invoke(null, new object[] { source, lambda.Compile() });
		}

		private static Dictionary Copy(this IDictionary toCopy)
		{
			Dictionary dictionaryCopy = new Dictionary();

			foreach (KeyValuePair item in toCopy)
			{
				dictionaryCopy.Add(item.Key, item.Value);
			}

			return dictionaryCopy;
		}
	}
}
Advertisements

Generic multi-property sorting using LINQ and Reflection

July 21, 2008

Recently I was tasked with the creation of a summary grid for a list of data objects.  All of the objects would be retrieved when the form containing the list was loaded, and there would be a default multi-column sort applied to the list.  After the initial load, more items could be added to the list, and the current sort would need to be applied.

There was some discussion amongst the team about how and where to sort.  Do we perform our ordering in the SQL call?  Quick, but only works on that initial load.  Do we simply rely on the Infragistics grids we’re using?  They do multi-column sorting but as soon as you add multiple bands to the grid (for master/detail views) the sort no longer works, though why I couldn’t even begin to take a guess at.  That’s when I remembered the OrderBy and ThenBy LINQ extension methods provided in the 3.5 Framework.

OrderBy, ThenBy and their reverse order cousins, OrderByDescending and ThenByDescending all take lambda expressions to define their sort order.  Usually a property is chosen as the sort candidate and the line would look something like this:

dateList.OrderBy(d => d.Year);

However, we could be sorting by any property in our object and multiple properties to boot.  Creating a big list of OrderBy and ThenBy statements for each property would simply be madness.  A better method would be to have a string key for the column which matches the property name and use Reflection to identify the property.  A dictionary of keys and their matching sort direction could be iterated over to provide multi-property sorting by storing the IOrderedEnumerable<T> object returned from the initial OrderBy/Descending call to gain access to ThenBy/Descending.  After encapsulating the whole thing in its own class, I ended up with this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using System.Reflection;

namespace ESC.SV.UI.Win.RATA.Helpers
{
	public static class ListSorter
	{
		public enum SortingOrder
		{
			Ascending,
			Descending,
		};

		public static IOrderedEnumerable<T> Sort<T>(IEnumerable<T> toSort, Dictionary<string, SortingOrder> sortOptions)
		{
			IOrderedEnumerable<T> orderedList = null;

			foreach (KeyValuePair<string, SortingOrder> entry in sortOptions)
			{
				if (orderedList != null)
				{
					if (entry.Value == SortingOrder.Ascending)
					{
						orderedList = orderedList.ApplyOrder<T>(entry.Key, "ThenBy");
					}
					else
					{
						orderedList = orderedList.ApplyOrder<T>(entry.Key, "ThenByDescending");
					}
				}
				else
				{
					if (entry.Value == SortingOrder.Ascending)
					{
						orderedList = toSort.ApplyOrder<T>(entry.Key, "OrderBy");
					}
					else
					{
						orderedList = toSort.ApplyOrder<T>(entry.Key, "OrderByDescending");
					}
				}
			}

			return orderedList;
		}

		private static IOrderedEnumerable<T> ApplyOrder<T>(this IEnumerable<T> source, string property, string methodName)
		{
			ParameterExpression param = Expression.Parameter(typeof(T), "x");
			Expression expr = param;
			foreach (string prop in property.Split('.'))
			{
				// use reflection (not ComponentModel) to mirror LINQ
				expr = Expression.PropertyOrField(expr, prop);
			}
			Type delegateType = typeof(Func<,>).MakeGenericType(typeof(T), expr.Type);
			LambdaExpression lambda = Expression.Lambda(delegateType, expr, param);

			MethodInfo mi = typeof(Enumerable).GetMethods().Single(
					method => method.Name == methodName
							&& method.IsGenericMethodDefinition
							&& method.GetGenericArguments().Length == 2
							&& method.GetParameters().Length == 2)
					.MakeGenericMethod(typeof(T), expr.Type);
			return (IOrderedEnumerable<T>)mi.Invoke(null, new object[] { source, lambda.Compile() });
		}
	}
}

Edit: Thanks to Karl for pointing out earlier that the original version didn’t work.  The values of the properties being sorted by were not getting extracted through the lambda expression. I have updated the code above to fix this issue and extended the functionality to include nested property sorting, so you can sort on something like “Name.FirstName” for an object. Thanks to this post for pointing me in the right direction.  I had to call .Compile()  on the lambda expression before I wouldn’t receive a runtime error.