所以我有一些排序逻辑需要在所有地方使用,所以我想我会尝试创建一个可以调用的通用方法,而不必复制和粘贴代码 30 次。
这就是我目前所拥有的方法
public static ICollection<T> SortBySections<T>(this IEnumerable<T> objectsToSort, IEnumerable<SECTION_ORDER> sections, Func<T, bool> ascendingPredicate, Func<T, object> ascendingOrder, Func<T, bool> descendingPredicate, Func<T, object> descendingOrder, Func<T, bool> missingItemPredicate)
{
List<T> results = new List<T>();
foreach (var sec in sections)
{
if (sec.MP_DIRECTION_C == "A")
{
results.AddRange(objectsToSort
.Where(ascendingPredicate)
.OrderBy(ascendingOrder));
}
else
{
results.AddRange(objectsToSort
.Where(descendingPredicate)
.OrderByDescending(descendingOrder));
}
}
if (results.Count < objectsToSort.Count())
{
foreach (var item in objectsToSort)
{
var missing = results.
Where(missingItemPredicate).
FirstOrDefault();
if (missing == null)
{
results.Add(item);
}
}
}
return results;
}
我试图这样称呼它
var results = equalities.SortBySections<StationEquality>(
TimetableHelper.GetSections(subdivCode),
new Func<StationEquality, bool>((rec) => rec.FromStation.SECTION_I == sec.SECTION_NUMBER_I && rec.FromStation.MP_PREFIX_I == sec.MP_PREFIX_I && rec.FromStation.MP_NUMBER_I >= sec.BEGIN_MP_NUMBER_I && rec.FromStation.MP_NUMBER_I <= sec.END_MP_NUMBER_I),
new Func<StationEquality, object>((rec) => rec.FromStation.MP_NUMBER_I),
new Func<StationEquality, bool>((rec) => rec.FromStation.SECTION_I == sec.SECTION_NUMBER_I && rec.FromStation.MP_PREFIX_I == sec.MP_PREFIX_I && rec.FromStation.MP_NUMBER_I >= sec.BEGIN_MP_NUMBER_I && rec.FromStation.MP_NUMBER_I <= sec.END_MP_NUMBER_I),
new Func<StationEquality, object>((rec) => rec.FromStation.MP_NUMBER_I),
new Func<StationEquality, bool>((rec) => rec.FromStation.STATION_I == rec.FromStation.STATION_I));
这甚至可能吗?Sec 参数在扩展方法之外不存在。任何帮助或将不胜感激。谢谢。