我有一个包含文件路径的字符串列表.
List<string> allFilesWithPathList = new List<string>(); allFilesWithPathList.Add(@"G:\Test\A.sql"); allFilesWithPathList.Add(@"G:\Test\B.sql"); allFilesWithPathList.Add(@"G:\Test\C.sql"); return allFilesWithPathList;
我有另一个列表,其中包含一个文件的子集 – 但它只有文件名;不是路径.
List<string> excludeList = new List<string>(); excludeList.Add("B.sql");
现在我需要从excludeList中不存在的allFilesWithPathList获取文件.目前,我正在使用EXCEPT,在创建另一个仅包含文件名的列表后,执行以下操作.
List<string> allFileNamesOnlyList = new List<string>(); foreach (string fileNameWithPath in allFilesWithPathList) { //Remove path and get only file name int pos = fileNameWithPath.LastIndexOf(@"\") + 1; string value = fileNameWithPath.Substring(pos,fileNameWithPath.Length - pos); allFileNamesOnlyList.Add(value); } //EXCEPT logic List<string> eligibleListToProcess = allFileNamesOnlyList.Except(excludeList).ToList();
LINQ中最好的方式是让这个逻辑工作,而不需要引入如上所述的其他列表?
注意:我正在使用.Net 4.5
完整代码
class Program { static void Main(string[] args) { List<string> allFilesWithPathList = GetAllFilesWithPath(); List<string> excludeList = new List<string>(); excludeList.Add("B.sql"); List<string> allFileNamesOnlyList = new List<string>(); foreach (string fileNameWithPath in allFilesWithPathList) { //Remove path and get only file name int pos = fileNameWithPath.LastIndexOf(@"\") + 1; string value = fileNameWithPath.Substring(pos,fileNameWithPath.Length - pos); allFileNamesOnlyList.Add(value); } //EXCEPT logic List<string> eligibleListToProcess = allFileNamesOnlyList.Except(excludeList).ToList(); //Print all eligible files foreach (string s in eligibleListToProcess) { Console.WriteLine(s); } Console.ReadLine(); } public static List<string> GetAllFilesWithPath() { List<string> allFilesWithPathList = new List<string>(); allFilesWithPathList.Add(@"G:\Test\A.sql"); allFilesWithPathList.Add(@"G:\Test\B.sql"); allFilesWithPathList.Add(@"G:\Test\C.sql"); return allFilesWithPathList; } }
解决方法
这应该工作
allFilesWithPathList.Where(x => !excludeList.Any(y => x.EndsWith(y)))