使用Reflection to Sort的扩展方法

时间:2009-09-25 20:34:33

标签: c# reflection sorting

我实现了一个扩展名“MyExtensionSortMethod”来对集合(IEnumerate)进行排序。这允许我用'entities.MyExtensionSortMethod()'替换代码,例如'entities.OrderBy(...).ThenByDescending(...)'(也没有参数)。

以下是一个实施示例:

//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);
}

然而,与它的相比,它似乎有点复杂,所以我想知道它们是否是另一种方式呢?

2 个答案:

答案 0 :(得分:0)

为什么不为此使用Predicate?它允许你pass your sorting conditions as a delegate

下面的示例没有排序,但它应该作为该技术的一个很好的例子:

 private class Book   
   {   
       public string Author { get; set; }   
       public string Name { get; set; }   
       public DateTime Published { get; set; }   
   }   

   //Create and fill a list of books   
   private List<Book> Books = new List<Book> {   
        new Book { Author="Mcconnell",Name="Code Complete", Published=new DateTime(1993,05,14) },  
        new Book { Author="Sussman",Name="SICP (2nd)", Published=new DateTime(1996,06,01) },  
        new Book { Author="Hunt",Name="Pragmatic Programmer", Published=new DateTime(1999,10,30) },  
    };  

    // returns a new collection of books containing just SICP and Pragmatic Programmer.  
    private IEnumerable<Book> BooksPublishedAfter1995()  
    {  
        return Books.FindAll(Book => Book.Published > new DateTime(1995, 12, 31));
    }  

http://www.rvenables.com/tag/predicates/

然后,现在我们又回到了OrderBy,不是吗?

答案 1 :(得分:0)

如果要为对象指定自定义排序,可以在类上实现IComparable接口。请参阅以下文章,了解如何执行此操作:

实施IComparable以对自定义对象进行排序
http://codebetter.com/blogs/david.hayden/archive/2005/02/27/56099.aspx

相关问题