简体   繁体   English

根据日历年排序月份

[英]Sorting months according to calendar year

I currently have some code that can sort strings in alphabetic order. 我目前有一些代码可以按字母顺序对字符串进行排序。 I would like for it to sort the months according to the calendar year. 我希望它根据日历年对月份进行排序。 I have seen ways to do it on this website but cant apply them to my code specifically. 我已经在该网站上看到了实现此目标的方法,但是无法将它们专门应用于我的代码。 What would I need to add to make it sort in order (January, February etc etc). 我需要添加什么才能使其按顺序排序(一月,二月等)。

Code to read months to array: 读取要数组月份的代码:

var month1Values = File
    .ReadAllLines(monthFilePath)
    .Select(x => new { Name = monthFilePath, Sort = DateTime.ParseExact(x, "MMMM", CultureInfo.InvariantCulture) })
    .ToArray(); 

Code to sort: 代码排序:

if (SortFile == 3)
{                 
    comparison1 = string.Compare(fileData[index].MonthValues, 
        fileData[index + 1].MonthValues) > 0;

    if (comparison1)
    {
        temp = fileData[index].MonthValues;
        fileData[index].MonthValues = fileData[index + 1].MonthValues;
        fileData[index + 1].MonthValues = temp;
        swap = true;
     }
 } 

Error appears where asterix is: asterix出现错误:

for (var index = 0; index < datasize; index++)
            {
                fileData[index] = new FileData
                {
            DayValues = day1Values[index],
            MonthValues = *month1Values[index]*,

                 };
            }

Error reads cannot convert type '< annonymous type: string Name, System.DateTime Sort >' to 'string'. 错误读取无法将类型“ <<匿名类型:字符串名称,System.DateTime排序>”转换为“字符串”。 How do I fix this problem? 我该如何解决这个问题?

You are creating anonymous data types in your Select instruction (first code box, line 3) instead of relying on DateTime type. 您将在Select指令(第一个代码框,第3行)中创建匿名数据类型,而不是依赖于DateTime类型。 The runtime don't know how to cast your anonymous type to String . 运行时不知道如何将匿名类型转换为String

This should work as expected: 这应该可以正常工作:

.Select(x => DateTime.ParseExact(x, "MMMM", CultureInfo.InvariantCulture))

Be aware that normal DateTime -> String cast involves creating a full date from only month given; 请注意,正常的DateTime > String强制转换涉及从给定的仅一个月创建一个完整的日期。 this involves assuming that day and year is current with hour, minute and second zeroed out. 这涉及假设日期和年份是当前的,将小时,分钟和秒置零。

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

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