Home > other >  Ordering substrings according to date in C#
Ordering substrings according to date in C#

Time:05-21

I have a large string containing multiple ID's in my reservation program for overview purpose.

string example = "ID01-20/05-Table1\n ID02-04/06-Table2\n ID03-21/05-Table1\n"

This is just an example, but the string could grow or shrink as reservations get deleted or added.

Currently, the overview is sorted based on ID's, but is it also possible using date or tables?

So it views as:

string example = "ID01-20/05-Table1\n ID03-21/05-Table1\n ID02-04/06-Table2\n"

Would be best if possible using Console.Display(); but I also wouldn't mind using something to generate a temporary string/list/array/whatever and displaying it that way.

I've seen it on static strings, but I'm not too sure how it would work as ID's get added and deleted.

CodePudding user response:

You can split the initial string into chunks

.Split('\n')

the match the date part in each chunk with a help of regular expression:

// one or two digits followed by slash and then one or two digits
Regex.Match(item, "[0-9]{1,2}/[0-9]{1,2}").Value

parse it into date

DateTime.TryParseExact(
   ...         
  "d/M", // day / Month format 
   null, 
   DateTimeStyles.AssumeLocal, 
   out var date)

and then order by for it.

Code:

  using System.Linq;
  using System.Text.RegularExpressions;

  ...

  string example = "ID01-20/05-Table1\n ID02-04/06-Table2\n ID03-21/05-Table1\n";

  string result = string.Join("\n", example
    .Split('\n')
    .OrderBy(item => DateTime.TryParseExact(
           Regex.Match(item, "[0-9]{1,2}/[0-9]{1,2}").Value,
          "d/M", 
           null, 
           DateTimeStyles.AssumeLocal, 
           out var date)
       ? date
       : DateTime.MaxValue));
  • Related