c# - 如何在 C# 中列出具有特定日期模式的所有子目录

标签 c# linq

我有一个目录,其中包含 FEB2014、MAR2013 等子目录。它还可以包含 Log 或其他子目录。

我的问题是如何找到具有特定日期模式(对于我的情况是 MMMyyyy)的所有子目录,例如 FEB2014、MAR2013。我更喜欢使用 LINQ

最佳答案

使用DateTime.TryParseExact喜欢:

DateTime temp;
var filtered = directories.Where(r => DateTime.TryParseExact(r, 
                                        "MMMyyyy", 
                                        CultureInfo.InvariantCulture, 
                                        DateTimeStyles.None, 
                                        out temp))
            .ToList();

这将只返回名称格式为 MMMyyyy 的目录。考虑一下您的 directories 数组是否包含如下内容:

//string[] directories = Directory.GetDirectories("yourPath");
string[] directories = new[] 
    {
        "FEB2014", 
        "MAR2013", 
        "LOG", 
        "SOMETHING", 
        "APR2014",
        "MAY2014"
    };

以上查询将返回四条记录。

FEB2014
MAR2013
APR2014
MAY2014

对于您的评论:

DirectoryInfo.GetDriectories 返回一个 DirectoryInfo 对象的数组,而不是直接返回一个字符串名称。您还需要为输出参数传递一个 DateTime 对象,您可以这样做:

DateTime temp;
var dirInfo = new DirectoryInfo(MyApp.App_Code.Global.FileLocation)
                    .GetDirectories()
                    .Where(d => DateTime.TryParseExact(d.Name, 
                    "MMMyyyy", CultureInfo.InvariantCulture, 
                    DateTimeStyles.None, 
                    out temp))
                    .OrderBy(d => d.LastAccessTime).Last();

关于c# - 如何在 C# 中列出具有特定日期模式的所有子目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23429988/

相关文章:

c# - 在 .NET Core 世界中中止线程的替代方案?

c# - EF 核心导航属性未加载

c# - 如何展平嵌套对象 (LINQ)

c# - 使用 FoxPro 的 LINQ?

C# linq 查询过滤子集合

c# - 重定向后 session 随机结束

c# - 枚举的 XML 序列化

c# - 将excel中的数据导入到多个表中

c# - 有条件的分组、求和、相减

C# Linq - 来自 SQL 的 SET 语法,即 SET abc(obj 的属性)WHERE xyz = true in IEnumerable<obj>