我收到的文件的文件名格式如下:
File_1242161_08112019010101PM 和 File_1710485_08112019111721AM。
我需要按照字符串第三部分中的日期时间的顺序处理这些文件。我还希望能够处理不遵循此特定格式的文件,例如:
File_666840
我想将列表从最早的日期时间到最晚进行排序,如果没有日期时间,则移至按文件名排序的列表底部。我尝试了以下方法:
List<string> sorted = filenames.OrderByDescending(file => file.Name.Split('_').Count())
.ThenBy(file => file.Name.Split('_').LastOrDefault().ToList());
这几乎让我到达那里,但 AM/PM 排序不正确。出于显而易见的原因,带有 01:01:01 PM 的文件名将在 11:17:21 AM 之前显示。完成我想要的任务的最高效且最 LINQ 的方式是什么?
最佳答案
只需使用 ParseExact
使用格式 MMddyyyyhhmmsstt
并选择 ValueTuple
或其他什么。
Converts the specified string representation of a date and time to its DateTime equivalent. The format of the string representation must match a specified format exactly or an exception is thrown.
由于现在已分开,您可以按照自己喜欢的方式订购,这只是一个示例
给定
var list = new List<string>()
{
"File_1242161_08112019010101PM",
"File_1710485_08112019111721AM",
"File_1710488",
"File_1710489",
"File_1710480"
};
代码
var orderedList = list.Select<string, (string Value, DateTime? Date)>(
x =>
{
var results = x.Split('_');
if (results.Length < 3)
return (x, (DateTime?)null);
return (x, DateTime.ParseExact(results[2], "MMddyyyyhhmmsstt", CultureInfo.InvariantCulture));
})
.OrderBy(x => x.Date == null)
.ThenBy(x => x.Date)
.ThenBy(x => x.Value)
.ToList();
使用
foreach (var item in orderedList)
Console.WriteLine(item.Value);
结果
File_1710485_08112019111721AM
File_1242161_08112019010101PM
File_1710480
File_1710488
File_1710489
注意:为了清晰起见,我使用了显式命名的元组,您可能可以使其看起来更简洁
注释 2:至于性能,还有其他解决方案...但是,除非您正在解码数百万个文件,否则您会发现获取文件名的调用超过了例程的成本
关于c# - 如何使用 string.split 对具有特定格式的字符串列表进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57516997/