0

所以我有一些排序逻辑需要在所有地方使用,所以我想我会尝试创建一个可以调用的通用方法,而不必复制和粘贴代码 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 参数在扩展方法之外不存在。任何帮助或将不胜感激。谢谢。

4

1 回答 1

1

更改参数 Funcs 以采用 2 个输入参数:recsec.

new Func<StationEquality, StationEquality, bool>((rec, sec) => ... )

然后在你的方法中,不要直接调用谓词。相反,将其包装在另一个谓词中,将提供的rec参数与您的参数一起传递sec。例如:

.Where((rec) => ascendingPredicate(rec, sec))

我没有编译也没有测试过这个。

于 2013-06-13T17:47:43.280 回答