Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass orderBy or OrderByDescending as parameter

Tags:

c#

I have method like this :

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

and the problem is that I can't stick all the time with OrderByDescending depends on groupByRule parameter sometimes it has to be orderByDescending or OrderBy

I don't want to depend on this parameter, so I could pass another one for that, Right now I call my method this way:

GetUsallyOpeningClosingHour(x => x.From)

or

GetUsallyOpeningClosingHour(x => x.To)

How can I pass orderBy type as well ?

like image 997
kosnkov Avatar asked Dec 09 '22 02:12

kosnkov


1 Answers

The simplest way is adding a parameter, which will specify an order in your collection.

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);
}

It could be a boolean or custom enum (I prefer enum, because it actually specifies a kind of ordering operation, while boolean specifies whether collection should be ordered by desc or not).

public enum OrderingType
{
    Ascending,
    Descending,
    None
}

Or you could provide an additional Func, which will perform an ordering operation. But its signature will be awkward.

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);
}
like image 174
Uładzisłaŭ Avatar answered Dec 10 '22 16:12

Uładzisłaŭ