Reputation: 175
I am trying to have multiple ||'s after my where clause based on the amount of strings in an array.
string[] searchStrings = new string[]{"test", "tester", "test3"};
var files = Directory.EnumerateFiles("FolderPath", "*.*", SearchOption.AllDirectories)
.Where(s => s.Contains(searchStrings[0]) || s.Contains(searchStrings[1]));
What it should do is search a folder for files, and if the file name contains each of the keywords from the array then it is put in files. Currently I can hardcode how many searches by adding more ||'s but I am wondering is there a way to do this automatically based on the size of the searchStrings array.
Upvotes: 0
Views: 73
Reputation: 5343
You can also use regular expression for this purpose
Regex searchPattern = new Regex("test|tester|test3"); // "test(3|er)?"
var files = Directory.EnumerateFiles("FolderPath", "*.*", SearchOption.AllDirectories)
.Where(s => searchPattern.IsMatch(s));
You can compose your pattern using:
string.Join("|", searchStrings);
I think regular expressions after precompiling may be even faster in some cases and gives you a lot more of flexibility
Upvotes: 0
Reputation: 6260
You can use .Any()
for instance:
.Where(dir => searchStrings.Any(s => dir.Contains(s)));
It will allow to get needed result by checking if directory name contains at least one searchString from searchStrings
collection.
Upvotes: 6