2

I have an string array

string[] days={ "1", "2", "6" }

I want to sort it according to DayOfWeek increasingly. For example "1" is Monday, "2" is Tuesday,"6"is saturday. Today is Thursday. So nearest one is Saturday,Monday,Tuesday. So final array will be

days={ "6", "1", "2" }

I couln't find any solution to sort them . How can I sort them.

Thanks in advance.

mr. pc_coder
  • 16,412
  • 3
  • 32
  • 54

3 Answers3

2

You can use LINQ for this:

string[] days = { "1", "2", "6" };

var today = (int)(DateTime.Now.DayOfWeek + 6) % 7;

var result = days
    .GroupBy(x => int.Parse(x) > today)
    .OrderByDescending(x => x.Key)
    .SelectMany(g => g.OrderBy(x => x));

Console.WriteLine("[{0}]", string.Join(", ", result));
# [6, 1, 2]

Which does the following:

  1. Splits the before and after days into two groups
  2. Sorts(descending) the after days before the before days
  3. Sorts(ascending) each group
RoadRunner
  • 25,803
  • 6
  • 42
  • 75
1

String is a bit complex to explain, so I use int instead.

Let the day-of-week always not smaller than today, then compare.

int[] days = { 1, 2, 6 };
int today;
Array.Sort(days, (d1, d2) =>
{
    if(d1 < today)
       d1 += 7;
    if(d2 < today)
       d2 += 7;
    return d1.CompareTo(d2);
});

Short form

Array.Sort(days, (d1, d2) => (d1 < today ? d1 + 7 : d1).CompareTo(d2 < today ? d2 + 7 : d2));

https://dotnetfiddle.net/QsVnIr

shingo
  • 18,436
  • 5
  • 23
  • 42
1

I don't know if you want in-place sorting or not, but in case you don't want to change your array (or chain more processing to the array), then you can use LINQ to sort the array

var today = (int)DayOfWeek.Thursday;
int weekDays = 7;
string[] days = { "1", "2", "6" };
var sortedDays = days.Select(int.Parse).OrderBy(d => d > today ? d - today : d + weekDays - today);

You can use a similar logic in the Array.Sort method too, if you wish to go that route

Vikhram
  • 4,294
  • 1
  • 20
  • 32