Reputation: 445
I have 2 List objects (simplified):
var fileList = Directory.EnumerateFiles(baseSourceFolderStr, fileNameStartStr + "*", SearchOption.AllDirectories);
var filterList = new List<string>();
filterList.Add("ThisFolderName");
filterList.Add("ThatFolderName");
I want to filter the fileLst to return only files containing any of folder names from the filterList. (I hope that makes sense..)
I have tried the following expression, but this always returns an empty list.
var filteredFileList = fileList.Where(fl => fl.Any(x => filterList.Contains(x.ToString())));
I can't seem to make sense of why I am getting nothing, clearly I am missing something, but I have no idea what.
[EDIT]
Ok, so it appears I should have been clearer in my question, I was trying to search for files in my fileList with a substring containing string values from my filterList. I have marked the answer below for those who are trying to do a similar thing.
Upvotes: 39
Views: 157843
Reputation: 15
Select * from employee Where cityID in ( select cityID from cities where countryID=1)
Upvotes: 0
Reputation: 5566
its even easier:
fileList.Where(item => filterList.Contains(item))
in case you want to filter not for an exact match but for a "contains" you can use this expression:
var t = fileList.Where(file => filterList.Any(folder => file.ToUpperInvariant().Contains(folder.ToUpperInvariant())));
Upvotes: 74
Reputation: 9966
Try the following:
var filteredFileSet = fileList.Where(item => filterList.Contains(item));
When you iterate over filteredFileSet (See LINQ Execution) it will consist of a set of IEnumberable values. This is based on the Where Operator checking to ensure that items within the fileList data set are contained within the filterList set.
As fileList is an IEnumerable set of string values, you can pass the 'item' value directly into the Contains method.
Upvotes: 10
Reputation: 4652
you can do that
var filteredFileList = fileList.Where(fl => filterList.Contains(fl.ToString()));
Upvotes: 1