Home > database >  C# - How to sort a list of string arrays ( List<string[]> ) by an item inside of the array?
C# - How to sort a list of string arrays ( List<string[]> ) by an item inside of the array?

Time:11-19

I have a dictionary.

Dictionary<string, List<string[]>> years = new Dictionary<string, List<string[]>>

The key represents a Year, and the values are each a list of string arrays, with each array only having 2 elements: a Date in that given year, and an ID number (not important). So if I were to look at just the year 2021, it looks about like this:

years[2021] == {
["09-30-2021","123456"],
["12-30-2021","654321"],
["03-30-2021","246810"],
["06-30-2021","135791"]
}

What I need to do is sort each of the lists of string arrays in this dictionary by the dates so that for any given year, the list of Date/ID pairs are sorted by the date. I'm not sure if I'll need Asc/desc order, so Ideally I would like to find a solution that would allow me to switch between either one fairly easily.

Any help would be tremendously appreciated!

CodePudding user response:

This should work:

public void SortYears(Dictionary<string, List<string[]>> years)
{
    foreach(var key in years.Keys)
    {
        var yearList = years[key];
        yearList = yearList.OrderBy(x => DateTime.ParseExact(x[0], "MM-dd-yyyy", null)).ToList();
        years[key] = yearList;
    }
}

I also echo the sentiment posted by others that you will be better off working with an actual object instead of a string array. What you're doing right now will lend itself to re-parsing the same date value over and over and over again, and thinks to cultural/internationalization concerns this is a slow and error-prone operation. But I understand if this is how you get the data in the first place.

CodePudding user response:

I assume that your dictionary actually looks like this:

Dictionary<int, List<string[]>> years = new Dictionary<int, List<string[]>>()
{
    { 2021, new List<string[]>()
        {
            new [] { "09-30-2021","123456" },
            new [] { "12-30-2021","654321" },
            new [] { "03-30-2021","246810" },
            new [] { "06-30-2021","135791" },
        }
    }
};

A better structure is Dictionary<int, SortedList<DateTime, string>>.

The transformation is quite easy:

Dictionary<int, SortedList<DateTime, string>> better =
    years
        .ToDictionary(
            x => x.Key,
            x => new SortedList<DateTime, string>(
                x.Value.ToDictionary(
                    y => DateTime.ParseExact(y[0], "MM-dd-yyyy", CultureInfo.InvariantCulture),
                    y => y[1])));

That gives me:

Sorted

  •  Tags:  
  • c#
  • Related