2014-10-05 125 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