mohammad hasson mohammad hasson -4 years ago 62
C# Question

sort a list of strings based by comparing the datetime portion of the string

I would like to sort a list of strings. the following example of pre-sorted strings:


"2017-03-21 17:14:36.111 I like Red"

"2017-03-21 17:14:35.333 I like Yellow"

"2017-03-21 17:14:36.111 I like Green"


I would like to sort the list using the datetime substring only.

private void MergeAndSort(string[] lines1, string[] lines2)
{
var entries = new List<string>();
entries.AddRange(lines1);
entries.AddRange(lines2);
entries.Sort();
foreach (string entry in entries)
{
CombinedrichTextBox.AppendText(entry);
}
}

Answer Source

Assuming your date/time string length stays constant you can do this.

        string[] entries =
        {
            "2017-03-21 17:14:36.380 I like Red",
            "2017-03-21 17:14:35.380 I like Yellow",
            "2017-03-21 17:14:36.380 I like Green"
        };

        var data = new List<Tuple<DateTime, string>>();

        foreach (var entry in entries)
        {
            data.Add(
                new Tuple<DateTime, string>(DateTime.Parse(entry.Substring(0, 23)), 
                entry.Substring(23)));
        }

        var sorted = data.OrderBy(e => e.Item1);
        entries = sorted.Select(e => $"{e.Item1} {e.Item2}").ToArray();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download