Extension method using Reflection to Sort
- by Xavier
I implemented an extension "MyExtensionSortMethod" to sort collections (IEnumerate). This allows me to replace code such as 'entities.OrderBy( ... ).ThenByDescending( ...)' by 'entities.MyExtensionSortMethod()' (no parameter as well).
Here is a sample of implementation:
//test function
function Test(IEnumerable<ClassA> entitiesA,IEnumerable<ClassB> entitiesB ) {
//Sort entitiesA , based on ClassA MySort method
var aSorted = entitiesA.MyExtensionSortMethod();
//Sort entitiesB , based on ClassB MySort method
var bSorted = entitiesB.MyExtensionSortMethod();
}
//Class A definition
public classA: IMySort<classA> {
....
public IEnumerable<classA> MySort(IEnumerable<classA> entities)
{
return entities.OrderBy( ... ).ThenBy( ...);
}
}
public classB: IMySort<classB> {
....
public IEnumerable<classB> MySort(IEnumerable<classB> entities)
{
return entities.OrderByDescending( ... ).ThenBy( ...).ThenBy( ... );
}
}
//extension method
public static IEnumerable<T> MyExtensionSortMethod<T>(this IEnumerable<T> e) where T : IMySort<T>, new()
{
//the extension should call MySort of T
Type t = typeof(T);
var methodInfo = t.GetMethod("MySort");
//invoke MySort
var result = methodInfo.Invoke(new T(), new object[] {e});
//Return
return (IEnumerable < T >)result;
}
public interface IMySort<TEntity> where TEntity : class
{
IEnumerable<TEntity> MySort(IEnumerable<TEntity> entities);
}
However, it seems a bit complicated compared to what it does so I was wondering if they were another way of doing it?