linq to extract specific subset
Given a directory of files (as a FileInfo array) how would I go about extracting all the filenames that have a corresponding filename with a specific extension.
For example, given a directory of the following files;
file1.txt
file1.txt.xml
file2.txt
file2.txt.xml
file3.xml
file3.xml.x开发者_高级运维ml
How would I extract file1.txt, file2.txt and file3.xml. Basically, I am looking for any file that has a correspoding entry with my given extension (xml in this case).
Thanks in advance.
This code will produce a list of the corresponding files (assuming that files is an IEnumerable<FileInfo>
:
var ext = ".xml"; // To match your example above
var list = files.Where(f => f.Extension.Equals(ext, StringComparison.OrdinalIgnoreCase))
.Select( f => Path.Combine(f.DirectoryName, Path.GetFileNameWithoutExtension(f.Name)))
.Where( n => File.Exists(n))
.ToList();
James's solution works. You can also use
files.Where(fi => fi.Extension == ext).ToList();
You could go with something like
string path = @"C:\Temp\XYZ";
string mainExtension = ".txt"; // optionally use
string companionExtension = ".xml";
var mainFiles = Directory.GetFiles(path); // or (path, "*" + mainExtension);
var companionFiles = Directory.GetFiles(path, "*" + companionExtension);
var filesWithCompanions = from file in mainFiles
from companion in companionFiles
where companion == file + companionExtension
select file;
If the directory is rather large, something like the below may be more optimal
var companionQuery = companionFiles.Select(file => file.Replace(Path.GetExtension(file), ""));
var companionSet = new HashSet<string>(companionQuery);
var filesWithCompanions = mainFiles.Where(companionSet.Contains);
var ext = ".xml";
FileInfo[] files = ...
var filered = files.Where(fi=> fi.Name.EndsWith(ext)).ToList();
// filtered is an List<FileInfo>
However, you probably don't need the ToList() (or the filters variable)
var ext = ".xml";
FileInfo[] files = ...
foreach(var file in files.Where(fi=> fi.Name.EndsWith(ext))
{
// do something with "file" here
}
精彩评论