skip to Main Content

How can I sort "YearMonth" text using Year & Month?

MyArray = ['2019APR', '2019AUG', '2019DEC', '2019FEB', '2019JAN',  
'2019JUL', '2019JUN', '2019MAR', '2019MAY', '2019NOV', '2019OCT',  
'2019SEP', '2020APR', '2020AUG', '2020DEC', '2020FEB', '2020JAN',  
'2020JUL', '2020JUN', '2020MAR', '2020MAY', '2020NOV', '2020OCT', '2020SEP']

Output Require

['2019JAN', '2019FEB', '2019MAR', '2019APR', '2019MAY', '2019JUN',  
'2019JUL', '2019AUG', '2019SEP', '2019OCT', '2019NOV', '2019DEC',  
'2020JAN', '2020FEB', '2020MAR', '2020APR', '2020MAY', '2020JUN',  
'2020JUL', '2020AUG', '2020SEP', '2020OCT', '2020NOV', '2020DEC']

I know Sort() will sort my array in alphabetical order but any optimal custom sort function for this?

2

Answers


  1. In c#, you can use the Array’s Sort overload that takes an Array and a Comparison as arguments:

    var arr = new[] { "2019APR", "2019AUG", "2019DEC", "2019FEB", 
                      "2019JAN", "2019JUL", "2019JUN", "2019MAR", 
                      "2019MAY", "2019NOV", "2019OCT", "2019SEP", 
                      "2020APR", "2020AUG", "2020DEC", "2020FEB", 
                      "2020JAN", "2020JUL", "2020JUN", "2020MAR", 
                      "2020MAY", "2020NOV", "2020OCT", "2020SEP" };
    
    Array.Sort(arr, (a, b) => ConvertToDateTime(a).CompareTo(ConvertToDateTime(b)));
    
    private DateTime ConvertToDateTime(string yyyyMMM) 
        => DateTime.ParseExact(
               yyyyMMM, 
               "yyyyMMM", 
               System.Globalization.CultureInfo.InvariantCulture);
    
    

    Note: You don’t have to use the ConvertToDateTime method, it’s just a helper to avoid writing the exact same ParseExact call twice.

    See a live demo on SharpLab (without the helper method)

    Login or Signup to reply.
  2. Simple :

                string[] MyArray = {"2019APR", "2019AUG", "2019DEC", "2019FEB", "2019JAN",
                    "2019JUL", "2019JUN", "2019MAR", "2019MAY", "2019NOV", "2019OCT",
                    "2019SEP", "2020APR", "2020AUG", "2020DEC", "2020FEB", "2020JAN",
                    "2020JUL", "2020JUN", "2020MAR", "2020MAY", "2020NOV", "2020OCT", "2020SEP" };
    
                string[] sortedArray = MyArray.Select(x => new { s = x, date = DateTime.ParseExact(x, "yyyyMMM", System.Globalization.CultureInfo.InvariantCulture) })
                    .OrderBy(x => x.date)
                    .Select(x => x.s)
                    .ToArray();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search