简体   繁体   English

在 C# 中,解析并按时间字符串排序的最佳方法是什么?

[英]In C#, what is the best way to Parse out and sort by time string?

I am reading and loading in files into Excel using C# VSTO and the filenames are something like this:我正在使用 C# VSTO 读取文件并将其加载到 Excel 中,文件名如下所示:

C:\myfiles\1000AM.csv
C:\myfiles\1100AM.csv
C:\myfiles\1200PM.csv
C:\myfiles\100PM.csv
C:\myfiles\200PM.csv

And then i am putting these in a list and need to sort these by "time".然后我把这些放在一个列表中,需要按“时间”对它们进行排序。

How can i convert the string in the format above into a time object that i can use to sort on?如何将上述格式的字符串转换为可用于排序的时间 object?

You need extract the time parts somehow and then compare them to each other.您需要以某种方式提取时间部分,然后将它们相互比较。

You could for example do this using a Comparison<string> .例如,您可以使用Comparison<string>来做到这一点。 Here is an example that uses the Span<T> type to do this without allocating any additional garbage:这是一个使用Span<T>类型来执行此操作而不分配任何额外垃圾的示例:

List<string> list = new List<string>() { ... }

list.Sort((a, b) => 
{
    //compare AM/PM
    int compareAmAndPm = a.AsSpan().Slice(a.Length - 6, 2)
        .CompareTo(b.AsSpan().Slice(b.Length - 6, 2), StringComparison.Ordinal);
    if (compareAmAndPm != 0)
        return compareAmAndPm;

    //compare the times as integers
    int index = a.LastIndexOf('\\');
    var firstTime = int.Parse(a.AsSpan().Slice(index + 1, a.Length - index - 7));

    index = b.LastIndexOf('\\');
    var secondTime = int.Parse(b.AsSpan().Slice(index + 1, b.Length - index - 7));


    return firstTime.CompareTo(secondTime);
});

It should give you a result of this:它应该给你一个结果:

C:\myfiles\1000AM.csv C:\myfiles\1000AM.csv
C:\myfiles\1100AM.csv C:\myfiles\1100AM.csv
C:\myfiles\100PM.csv C:\myfiles\100PM.csv
C:\myfiles\200PM.csv C:\myfiles\200PM.csv
C:\myfiles\1200PM.csv C:\myfiles\1200PM.csv

From practice we figured out, that a Time or Date on it's own does not work 99% of the cases.从实践中我们发现,在 99% 的情况下,仅靠时间或日期是行不通的。 We need both plus the timezone to have any hope of processing them meaningfully.我们需要两者加上时区才能有意义地处理它们。

That is why we only have things like DateTime , nowadays.这就是为什么我们现在只有DateTime这样的东西。 Ideally those file names should consist of the full DateTime, in UTC and Invariant culture.理想情况下,这些文件名应包含完整的 DateTime,采用 UTC 和 Invariant 文化。 If you got the option to change how those are created, use it.如果您可以选择更改创建方式,请使用它。

However if you consistently only have one part that is not an issue: DateTime simply used default values for the other two.但是,如果您始终只有一个不是问题的部分: DateTime只是对其他两个使用默认值。 And as those two will be consistent, they will work.由于这两个将是一致的,它们将起作用。 The only issue will be a finding a culture setting that eats that AM/PM format.唯一的问题将是找到一种能够适应 AM/PM 格式的文化环境。

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

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