2011-09-08 3 views
1

안정적인 정렬을 사용하기 위해 SortableBindingList을 수정하는 방법은 example입니다. 그러나 updated version of SortableBindingList이 있습니다. 안정된 정렬을 사용하기 위해이 새 버전을 수정하는 가장 좋은 방법은 무엇입니까? SortableBindingList의 사용자가 SortableBindingList의 사용자에게 (느린) 안정적인 정렬 또는 (더 빠른) 기본 정렬을 사용할지 결정하도록 할 수있는 SortableBindingList 플래그가 필요하다고 생각합니다.SortableBindingList에 안정된 정렬을 사용하는 가장 간단한 방법

감사

당신은 List<T> 안정된 정렬 확장 메서드를 작성하여이 문제를 해결할 수

답변

5

:

itemsList.Sort(comparer); 

: 다음

public static class ListExtensions 
{ 
    public static void StableSort<T>(this List<T> list, IComparer<T> comparer) 
    { 
     var pairs = list.Select((value, index) => Tuple.Create(value, index)).ToList(); 
     pairs.Sort((x, y) => 
      { 
       int result = comparer.Compare(x.Item1, y.Item1); 
       return result != 0 ? result : x.Item2 - y.Item2; 
      }); 
     list.Clear(); 
     list.AddRange(pairs.Select(key => key.Item1)); 
    } 
} 

SortableBindingList 변경이 라인의 새 버전 ~까지 :

itemsList.StableSort(comparer); 

목록의 항목 인덱스에 보조 키가 추가 된 불안정한 정렬을 사용하면됩니다. 이 버전은 병적으로 느린 삽입 유형을 사용하여 안정적인 정렬을 수행하지 않으므로 일반적으로 사용하기에 충분히 빠릅니다.

+0

환상적입니다. 감사합니다. – Jimmy

관련 문제