简体   繁体   English

基于日期 20210419 的字符串排序列表

[英]sorting list of strings based on date 20210419

I have.我有。 list of files, names of the files are log20211904.json what would be the best way to sort this name based on the date that is included in the name of the file?文件列表,文件名是log20211904.json根据文件名中包含的日期对该名称进行排序的最佳方法是什么? What I get now from my method substring is 20210419 which is not valid date time.我现在从我的方法 substring 得到的是 20210419,它不是有效的日期时间。 I wonder how to do it effectively and get valid DateTimeOffset from 20210419我想知道如何有效地做到这一点并从 20210419 获得有效的 DateTimeOffset

I was thinking我刚在想

var orderedFIle = new List<LogFile>();
        
var fileDetail = new LogFile()
{
    FileName = "log20210419",

};
var fileDetailtest = new LogFile()
{
    FileName = "log20210420",

};
var test = fileDetail.FileName.Substring(3, 8);
Console.WriteLine(test);
orderedFIle.Add(fileDetail);
orderedFIle.Add(fileDetailtest);

var  list = orderedFIle.OrderByDescending(f => DateTime.Parse(f.FileName.Substring( 3,8)));
foreach (var VARIABLE in list)
{
    Console.WriteLine(VARIABLE.FileName);
}

But the date is actually without separators.但日期实际上没有分隔符。 What would be the best approach什么是最好的方法

Since the date in the string is already in a sortable format you can just sort by the full log name.由于字符串中的日期已经是可排序的格式,因此您可以按完整的日志名称进行排序。

For example:例如:

var l = new List<LogFile>();
l.Add(new LogFile(){FileName = "log20210419"});
l.Add(new LogFile(){FileName = "log20210420"});
l.Add(new LogFile(){FileName = "log20210101"});
foreach (var f in l.OrderByDescending(f => f.FileName))
{
    Console.WriteLine(f.FileName);
}

prints印刷

log20210420
log20210419
log20210101

If you really want to parse then you can use ParseExact :如果你真的想解析,那么你可以使用ParseExact

DateTime.ParseExact(f.FileName, "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture)

Define a class as follows.如下定义 class。

/// <summary>
/// Use a regular expression to validate the file name and extract the date parts.
/// Implement IComparable to define a default sort order.
/// </summary>
public class JsonLogFileName : IComparable<JsonLogFileName>
{
    // Private data members.
    private string fileName;
    private DateTime fileDate;

    // Public accessor methods.
    public String FileName => this.fileName;

    public DateTime FileDate => this.fileDate;

    /// <summary>
    /// Class constructor.
    /// </summary>
    /// <param name="fileName"></param>
    public JsonLogFileName(string fileName) {

        // Use a regular expression to validate the file name
        // and extract the date parts.
        Match m = Regex.Match(fileName, @"^log(\d{4})(\d{2})(\d{2}).json$");
        if (!m.Success) {
            throw new ArgumentException();
        }

        this.fileName = fileName;

        int year = int.Parse(m.Groups[1].Value);
        int month = int.Parse(m.Groups[2].Value);
        int day = int.Parse(m.Groups[3].Value);

        this.fileDate = new DateTime(year, month, day);
    }

    // Default sort order
    public int CompareTo(JsonLogFileName other) {
        return DateTime.Compare(this.FileDate, other.FileDate);
    }
}

You can use it like this.你可以像这样使用它。

public static void Main(String[] args) {

    List<JsonLogFileName> jsonLogFileNameList = new List<JsonLogFileName> {
        new JsonLogFileName("log20210419.json"),
        new JsonLogFileName("log20210418.json"),
        new JsonLogFileName("log20210417.json"),
        new JsonLogFileName("log20210416.json"),
        new JsonLogFileName("log20210415.json"),
    };

    jsonLogFileNameList.Sort();

    foreach (JsonLogFileName jsonFileName in jsonLogFileNameList) {
        Console.WriteLine($"{jsonFileName.FileName}: {jsonFileName.FileDate}");
    }

    Console.WriteLine("Press any key to continue.");
    Console.ReadKey();
}

Use IComparable使用 IComparable

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace HotelManagement
{
    public class Program
    {
        public static void Main(string[] args)
        {
            string[] filenames = {
                                     "log20211904.json",
                                     "log20211804.json",
                                     "log20211904.json",
                                     "log20210903.json",
                                     "log20211902.json",
                                     "log20211910.json",
                                     "log20211909.json"
                                 };

            string[] results = filenames.OrderBy(x => new SortFileName(x)).ToArray();

 
        }
    }
    public class SortFileName : IComparable<SortFileName>
    {
        private DateTime date { get; set; } 

        public SortFileName(string filename)
        {
            date = DateTime.ParseExact(filename.Substring(3,8), "yyyyddMM", System.Globalization.CultureInfo.InvariantCulture);
        }
        public int CompareTo(SortFileName other)
        {
            return this.date.CompareTo(other.date);

        }
    }
 
}

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

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