0

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.

  • I'd start by splitting on newline. https://stackoverflow.com/a/1547483 – Robert Harvey May 20 '22 at 14:28
  • But it would be better if you could go back to the code that's generating these strings, and start from there, because you have access to better data for performing the ordering. – Robert Harvey May 20 '22 at 14:30
  • Write a parser/serializer to get individual reservations from that string(deserialize). Sort them then and then serialize after that back into your string format. – Ralf May 20 '22 at 14:31
  • String parsing is a notoriously *slow* operation. It is a better practice to put your data into a *collection of objects (classes)* of some sort, then you can use LINQ to order the data any way you want for display. You can override the `ToString()` method on each object to control the string that represents the data within it. – NightOwl888 May 20 '22 at 14:36

1 Answers1

0

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));
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215