2009-09-25 4 views
0

컬렉션 (IEnumerate)을 정렬하기 위해 "MyExtensionSortMethod"확장을 구현했습니다. 이것은 'entities.OrderBy (...) .ThenByDescending (...)'과 같은 코드를 'entities.MyExtensionSortMethod()'(매개 변수 없음)로 대체하도록 허용합니다. 조금 그들이 그 일을 다른 방법이라면 그렇게 내가 궁금해서 무엇에 비해 복잡한 것 같습니다 그러나Reflection to Sort를 사용하는 확장 메서드

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

: 여기

구현의 샘플입니다?

+1

개체 정렬 : 그것을 수행하는 방법에 대해 설명의 다음 문서를 참조하십시오? 당신의 모든 엔티티 클래스가 그 타입의 정렬 콜렉션을 완전히 캡슐화하는 자신의'MySort' 메소드를 가지고 있다면, 왜 직접 호출하지 않을까요? 확장 방법의 목적은 무엇입니까? –

+0

각 엔티티에는 MySort 메소드가 있습니다. 그러나 수집은 아닙니다. 어쩌면 내가 뭔가를 놓친 것일 수도 있지만 다른 방법을 모른다. –

+0

그래서'MySort'를 정적으로 만들고,'IEnumerable '을 가지고 있다면'ClassA.MySort'를 호출하고,'IEnumerable '를 가지고 있다면'ClassB.MySOrt'를 호출하십시오. –

답변

0

여기에 Predicate을 사용하지 않으시겠습니까? 그것은 pass your sorting conditions as a delegate 수 있습니다.

아래 예제 정렬되지 않지만,이 기술의 괜찮은 예로서 봉사해야한다 : 이제 우리는 다시있는 OrderBy에있어, 다시 그 다음

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/

,하지 우리?

+0

좀 더 구체적으로 알려주시겠습니까? 작은 표본으로? 고맙습니다. –

+0

나는 모든 것을 조립할 준비가되지 않았다. 나는 왜 당신이 당신의 예를 위해 OrderBy만큼 우아한 것을 떨어 뜨린 지 알아 내려고하고있다. 그러나 나는 그것을 줄 것이다. 내 편집을 참조하십시오. –

+0

전체 프로젝트에서 우리는 주로 많은 컬렉션 작업을해야합니다. 언제든지 업데이트 할 수 있으며 그래프를 기반으로 정렬해야 할 수도 있습니다. 기관 .OrderBy (예 => e.Parent.Parent.Parent.Something) .ThenBy (예 => e.Parent : 당신 같은 끝낼 수있는 마지막() 엔티티를 잡기 위해 예를 들어 . 부모님.) ... .TheBy (e => e.Something) .Last() 자주 발생하는 경우를 제외하고는 괜찮습니다. 또한 유지하기가 어려울 수 있습니다. DataLoadOptions은 해결책 일 수 있지만 Google 사례에 맞지 않습니다. 그래서 엔티티 SortMe()와 같은 것을 원합니다. Last() SortMe는 한 번만 정의됩니다. –