我需要一个带有两个参数的扩展方法:一个目标 IList<T>和自定义比较器。
public static void CustomSort<T>( IList<T> target, IComparer<T> comparer )
{
...
}
扩展方法的工作是按照自定义比较器指示的顺序排列目标的元素。
以下是一些不会起作用的解决方案:
List<T>.Sort进行就地排序,这基本上就是我所追求的。但我不能假设目标的具体类型是List<T>.- LINQ 提供了一些解决方案,但不幸的是,它们将结果输出为新的可枚举而不是修改目标列表。
相反,我需要目标的 Remove和 Insert要调用的方法以将其元素放入正确的顺序。目标列表可能是可观察的,因此重要的是解决方案不会执行比获得所需顺序所需的更多的删除和插入操作。
请您参考如下方法:
我认为这样的事情对你有用。
我们对偏移量数组进行排序,然后确定需要应用的增量集合,最后应用它们来生成新排序的 IList。
public static void CustomSort<T>( IList<T> list , IComparer<T> comparer )
{
int[] unsorted = Enumerable.Range(0,list.Count).ToArray() ;
int[] sorted = Enumerable.Range(0,list.Count).OrderBy( x => list[x] , comparer ).ToArray() ;
var moves = sorted.Zip( unsorted , (x,y) => new{ Src = x , Dest = y , } ).Where( x => x.Src != x.Dest ).OrderBy( x => x.Src ).ToArray() ;
// at this point, moves is a list of moves, from a source position to destination position.
// We enumerate over this and apply the moves in order.
// To do this we need a scratch pad to save incomplete moves, where an existing item has
// been over-written, but it has not yet been moved into its final destination.
Dictionary<int,T> scratchPad = new Dictionary<int, T>() ; // a parking lot for incomplete moves
foreach ( var move in moves )
{
T value ;
// see if the source value is on the scratchpad.
// if it is, use it and remove it from the scratch pad.
// otherwise, get it from the indicated slot in the list.
if ( scratchPad.TryGetValue( move.Src , out value ) )
{
scratchPad.Remove( move.Src );
}
else
{
value = list[ move.Src ] ;
}
// if the destination is after the source position, we need to put
// it on the scratch pad, since we haven't yet used it as a source.
if ( move.Dest > move.Src )
{
scratchPad.Add( move.Dest , list[ move.Dest ]);
}
// finally, move the source value into its destination slot.
list[ move.Dest ] = value ;
}
return ;
}
