要使用內置排序功能提供就地排序,您需要編寫一個實現IComparer<T>
的類。
例如:
class CompareWithDelegate<TOnObject, TSort> : IComparer<TOnObject>
{
Func<TOnObject, TSort> evaluator;
IComparer comparer = Comparer.Default;
bool ascending;
public CompareWithDelegate(Expression<Func<TOnObject, TSort>> expr, bool ascending = true)
{
evaluator = expr.Compile();
this.ascending = ascending;
}
public int Compare(TOnObject left, TOnObject right)
{
var leftVal = evaluator(left);
var rightVal = evaluator(right);
return (ascending ? 1 : -1) * comparer.Compare(leftVal, rightVal);
}
}
然後:
void CreateSortedReport<TSort>(List<MyObject> list, Expression<Func<MyObject, TSort>> sortExpression, bool ascending = true)
{
list.Sort(new CompareWithDelegate<MyObject, TSort>(sortExpression));
list.Dump();
}
注意,list
必須List<MyObject>
,不IList<MyObject>
。
或者,如果你不需要它是原地的,你有兩個選擇:
更改簽名Func<MyObject, TSort>
:
void CreateSortedReport<TSort>(List<MyObject> list, Func<MyObject, TSort> sortExpression, bool ascending = true)
{
var t =
ascending
? list.OrderBy (sortExpression)
: list.OrderByDescending(sortExpression);
}
或編譯的飛行表達:
void CreateSortedReport<TSort>(List<MyObject> list, Expression<Func<MyObject, TSort>> sortExpression, bool ascending = true)
{
var method = sortExpression.Compile();
var t =
ascending
? list.OrderBy (method)
: list.OrderByDescending(method);
}
來源
2015-12-22 03:45:38
Rob
@DioPhung,如果你在'IList的'操作,可以替代使用'Func鍵'你的表達單子。 –
@sstan:沒錯,我想在該方法內部進行就地排序。 –