实现通用扩展

时间:2014-10-05 15:51:41

标签: c# linq

我有这种扩展IList<>的方法我需要实现特殊订购。它需要IList IDisplayOrderable和整数forRandom,并返回一个有序列表,但随机化DisplayOrder等于forRandom参数的项。

public static IList<IDisplayOrderable> ReorderList(this IList<IDisplayOrderable> lstMain, int forRandom)
{
    List<IDisplayOrderable> result = new List<IDisplayOrderable>();
    Random rnd = new Random();
    result.AddRange(lstMain.Where(x => x.DisplayOrder.GetValueOrDefault(int.MaxValue) < forRandom).OrderBy(x => x.DisplayOrder.GetValueOrDefault(int.MaxValue)));
    result.AddRange(lstMain.Where(x => x.DisplayOrder.GetValueOrDefault(int.MaxValue) == forRandom).Shuffle(rnd));
    result.AddRange(lstMain.Where(x => x.DisplayOrder.GetValueOrDefault(int.MaxValue) > forRandom).OrderBy(x => x.DisplayOrder.GetValueOrDefault(int.MaxValue)));
    return result;
}

IDisplayOrderable是一个简单的界面,可以公开DisplayOrder来订购不同的类型。

public interface IDisplayOrderable
{
    Nullable<int> DisplayOrder { get; set; }
}

我希望实现相同的功能,但是对于我希望明确设置&#39; OrderBy&#39;的通用列表。属性, 例如:MyList.ReorderList(x=>x.DisplayOrder, 1000),还有MyOtherList.ReorderList(x=>x.OtherDisplayOrder, 1000)。  我读了一些关于做这个的反思,但是没有设法让事情发挥作用。 任何帮助或指示将不胜感激

1 个答案:

答案 0 :(得分:2)

更改ReorderList方法,使其接受委托返回所需属性的值:

public static IList<T> ReorderList(this IList<T> lstMain,Func<T,int?> getter, int forRandom)
{
    List<T> result = new List<T>();
    Random rnd = new Random();
    result.AddRange(lstMain.Where(x => getter(x).GetValueOrDefault(int.MaxValue) < forRandom).OrderBy(x => getter(x).GetValueOrDefault(int.MaxValue)));
    result.AddRange(lstMain.Where(x => x.getter(x).GetValueOrDefault(int.MaxValue) == forRandom).Shuffle(rnd));
    result.AddRange(lstMain.Where(x => getter(x).GetValueOrDefault(int.MaxValue) > forRandom).OrderBy(x => xgetter(x).GetValueOrDefault(int.MaxValue)));
    return result;
}

并称之为:

MyOtherList.ReorderList(x=>x.OtherDisplayOrder, 1000)
相关问题