如何使用LINQ从目录中过滤文件? [英] How to filter files from directory using LINQ?
问题描述
在我的程序c#中,我正在使用LINQ从目录中提取所有文件以进行如下处理
In my program c#, i am using LINQ to fetch all file from directory for processing as following
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,其他文件也相同.
But In my case i have xml and txt files of same name like A.xml and A.txt similarly B.xml and B.txt and same for others.
我想使用LINQ来获取两个相同名称的文件以进行如下处理
I want to use LINQ to fetch both files of same name for processing as following
Processfile(字符串xmlfile,字符串txtfile)
Processfile(string xmlfile, string txtfile)
根据我上面的代码,我从目录中获取所有文件(xml,txt),但我不知道进一步进行操作.
As per my above code, i am getting all files(xml, txt) from directory, but i don't know to proceed further.
请帮助过滤名称相同但扩展范围不同的文件?
Please help to filter the files of same name but different extention?
推荐答案
You can use the Linq GroupBy method to do this, eg:
DirectoryInfo directory = new DirectoryInfo(sDirectory);
var filePairs = directory
.GetFiles("*.xml")
.Union(directory.GetFiles("*.txt"))
.GroupBy(file => file.Name);
或者,如果您只希望成对获取文件,则:
Or if you wish to get just the files in pairs:
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);
这篇关于如何使用LINQ从目录中过滤文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!