Extension method using Reflection to Sort
Posted
by Xavier
on Stack Overflow
See other posts from Stack Overflow
or by Xavier
Published on 2009-09-25T20:34:33Z
Indexed on
2010/05/12
23:04 UTC
Read the original article
Hit count: 400
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?
© Stack Overflow or respective owner