所以我有一些我需要在整个地方使用的排序逻辑,所以我想我会尝试创建一个我可以调用的通用方法,而不必复制和粘贴代码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参数。任何帮助或将不胜感激。谢谢。
答案 0 :(得分:1)
更改参数Funcs以获取2个输入参数:rec
和sec
。
new Func<StationEquality, StationEquality, bool>((rec, sec) => ... )
然后在你的方法中,不要直接调用谓词。而是将其包装在另一个谓词中,并传递提供的rec
参数以及sec
参数。例如:
.Where((rec) => ascendingPredicate(rec, sec))
我没有编译或测试过这个。