简体   繁体   English

实施通用扩展

[英]Implementing a generic extension

I have this method that extends IList<> for special ordering I need to implement. 我有扩展IList <>的方法,可以实现特殊的排序。 It takes an IList of IDisplayOrderable and an integer forRandom , and returns an ordered list but randomizing the items that have the DisplayOrder equals to the forRandom parameter. 它接受IDisplayOrderable forRandom和一个整数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;
}

The IDisplayOrderable is a simple interface that expose the DisplayOrder for ordering different types. IDisplayOrderable是一个简单的接口,它公开DisplayOrder以订购不同的类型。

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

I want to achieve the same functionality but for a generic list that I wish to explicit set the 'OrderBy' property, something like: MyList.ReorderList(x=>x.DisplayOrder, 1000) but also MyOtherList.ReorderList(x=>x.OtherDisplayOrder, 1000) . 我想要实现相同的功能,但对于希望显式设置'OrderBy'属性的通用列表, MyList.ReorderList(x=>x.DisplayOrder, 1000)类似于: MyList.ReorderList(x=>x.DisplayOrder, 1000)以及MyOtherList.ReorderList(x=>x.OtherDisplayOrder, 1000) I read some about reflection to do this but haven't managed to get something working. 我读了一些有关反射的方法,但是还没有设法使它起作用。 Any help or direction would be appreciated 任何帮助或指示将不胜感激

Change ReorderList method so that it accepts a delegate returning the value of your desired property: 更改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;
}

and call it like: 并这样称呼:

MyOtherList.ReorderList(x=>x.OtherDisplayOrder, 1000)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM