2014-10-05 693 views
1

我有这种方法扩展IList <>用于需要实现的特殊排序。它需要一个IDisplayOrderable的IList和一个整数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; } 
} 

我要实现相同的功能,但对于我想明确的设置“排序依据”属性的通用列表, 是这样的:MyList.ReorderList(x=>x.DisplayOrder, 1000)MyOtherList.ReorderList(x=>x.OtherDisplayOrder, 1000)。 我阅读了一些关于反射的文章,但没有设法找到一些工作。 任何帮助或方向将不胜感激

回答

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) 
+0

的伟大工程。谢谢!需要将添加到ReorderList (... – Issac 2014-10-05 16:46:48