How to filter files from directory using LINQ?

后端 未结 1 937
不思量自难忘°
不思量自难忘° 2021-01-07 05:22

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(sDire         


        
1条回答
  •  走了就别回头了
    2021-01-07 06:04

    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);
    

    0 讨论(0)
提交回复
热议问题