繁体   English   中英

C# - 如何对字符串列表 arrays (列表<string[]> ) 通过数组内的一个项目?</string[]>

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

我有一本字典。

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

键代表年份,值是字符串 arrays 的列表,每个数组只有 2 个元素:给定年份的日期和 ID 号(不重要)。 因此,如果我只看 2021 年,它看起来是这样的:

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

我需要做的是按日期对该字典中的每个字符串 arrays 列表进行排序,以便对于任何给定年份,日期/ID 对列表按日期排序。 我不确定我是否需要 Asc/desc 顺序,所以理想情况下,我想找到一种解决方案,让我可以相当轻松地在两者之间切换。

任何帮助将不胜感激!

这应该有效:

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;
    }
}

我也回应其他人发表的观点,即您最好使用实际的 object 而不是字符串数组。 您现在所做的将有助于一遍又一遍地重新解析相同的日期值,并且考虑到文化/国际化问题,这是一个缓慢且容易出错的操作。 但我了解这是否是您首先获取数据的方式。

我假设你的字典实际上是这样的:

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" },
        }
    }
};

更好的结构是Dictionary<int, SortedList<DateTime, string>>

转换非常简单:

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])));

这给了我:

已排序

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM