【问题标题】:How to filter files from directory using LINQ?如何使用 LINQ 从目录中过滤文件?
【发布时间】:2011-11-30 17:01:13
【问题描述】:

在我的程序 c# 中,我使用 LINQ 从目录中获取所有文件以进行如下处理

var FilesToProcess = from filePath in Directory.GetFiles(sDirectory)
                        where File.GetCreationTime(filePath).BusinessDaysUntil(DateTime.Today)
                        select filePath;
if (FilesToProcess.Any())
{
    List<string> process = (from string s in FilesToProcess
                            where ((s.EndsWith(".ext")) || (s.EndsWith(".xml")))
                            select s).ToList();
}

但就我而言,我有同名的 xml 和 txt 文件,例如 A.xml 和 A.txt,类似 B.xml 和 B.txt,其他文件也一样。

我想使用 LINQ 来获取两个同名文件进行如下处理

进程文件(字符串 xmlfile,字符串 txtfile)

根据我上面的代码,我正在从目录中获取所有文件(xml、txt),但我不知道继续进行。

请帮忙过滤同名但扩展名不同的文件?

【问题讨论】:

    标签: c# .net linq


    【解决方案1】:

    您可以使用Linq GroupBy method 来执行此操作,例如:

    DirectoryInfo directory = new DirectoryInfo(sDirectory);
    var filePairs = directory
                .GetFiles("*.xml")
                .Union(directory.GetFiles("*.txt"))
                .GroupBy(file => file.Name);
    

    或者,如果您只想成对获取文件:

    var filePairs = directory
                .GetFiles("*.xml")
                .Union(directory.GetFiles("*.txt"))
                .GroupBy(file => file.Name)
                .Select(grp => new
                {
                     XmlFile = grp.FirstOrDefault(file => file.Extension == "xml"),
                     TxtFile = grp.FirstOrDefault(file => file.Extension == "txt")
                })
                .Where(pair => pair.XmlFile != null && pair.TxtFile!= null);
    

    【讨论】:

    • 如果使用 .NET4 或更高版本,最好使用 EnumerateFiles 而不是 GetFiles:它会流式传输结果而不是敲出单个数组。
    • 我使用了上面的代码,我在目录中有 2 个 txt 和 2 个 xml 文件。我越来越空了。你能帮我做错什么吗,我复制了完全相同的代码
    • @HemantKothiyal 请发布您的更新代码和您遇到的错误。
    猜你喜欢
    • 2012-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-24
    • 2019-01-06
    • 1970-01-01
    • 2012-02-25
    相关资源
    最近更新 更多