c# - 传递 orderBy 或 OrderByDescending 作为参数

标签 c#

我有这样的方法:

GetUsallyOpeningClosingHour(Func<OpeningDay, TimeSpan> groupByRule)
{
var openingClosingHours = listOfSpecificDayOfWeek.GroupBy(groupByRule).OrderByDescending(x => x.Key);
}

问题是我不能一直坚持 OrderByDescending 取决于 groupByRule 参数,有时它必须是 orderByDescending 或 OrderBy

我不想依赖这个参数,所以我可以为此传递另一个参数, 现在我这样调用我的方法:

GetUsallyOpeningClosingHour(x => x.From)

GetUsallyOpeningClosingHour(x => x.To)

如何传递 orderBy 类型?

最佳答案

最简单的方法是添加一个参数,该参数将指定您的集合中的顺序。

public void GetUsallyOpeningClosingHour(
    Func<OpeningDay, TimeSpan> groupByRule, 
    bool orderByDesc = false)
{
    var groupedDays = listOfSpecificDayOfWeek.GroupBy(groupByRule);

    var openingClosingHours =
        orderByDesc
            ? groupedDays.OrderByDescending(x => x.Key)
            : groupedDays.OrderBy(x => x.Key);
}

它可以是一个boolean或自定义的enum(我更喜欢enum,因为它实际上指定了一种排序操作,而boolean指定集合是否应该按 desc 排序。

public enum OrderingType
{
    Ascending,
    Descending,
    None
}

或者您可以提供一个额外的 Func,它将执行排序操作。但是它的签名会很尴尬。

public static void GetUsallyOpeningClosingHour(
    Func<OpeningDay, TimeSpan> groupByRule,
    Func<IEnumerable<IGrouping<TimeSpan, OpeningDay>>,
         IEnumerable<IGrouping<TimeSpan, OpeningDay>>> orderBy)
{
    var groupedDays = listOfSpecificDayOfWeek.GroupBy(groupByRule);
    var openingClosingHours = orderBy(groupedDays);
}

关于c# - 传递 orderBy 或 OrderByDescending 作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31661781/

相关文章:

c# - 重定向到操作 ASP .NET MVC

c# - 下载大型 Azure 存储 Blob 的最快方法?

c# - 滚动条的样式不起作用

c# - 为什么我不能在类上实现接口(interface),用具体类型替换接口(interface)?

c# - SQL Where in to Linq with DataTable

c# - 配置文件属性不起作用

c# - WPF Tab 键导航

c# - EntityFramework 确定子集合是否包含项目而不获取整个集合

c# - 回发后 ViewState 变量重置

c# - 从按钮取消异步任务