Reputation: 129
Suppose I have a list of strings. These strings will be a part of the directory name that I want to open.
var listOfStrings = new List<string>(){"Foo", "Bar", "LocalHost", "SomeIPAddress"};
If this is my list, my directories might look like this:
So I have the code here to load the directory info into a list:
m_jsonDirectories = new DirectoryInfo(@"C:\ProgramData\SCLDDB\ReportLogs\")
.GetDirectories()
.OrderByDescending(p_f => p_f.LastWriteTime)
.ToList();
Right now, I can load all the directories in the master directory into my variable, but I want to add something like:
.Where(x => x.Name.Contains(/*A string found in my List above*/)
Edit: in the above statement, the parameter x is of type DirectoryInfo. So x.Name should return the Name of the Directory.
I don't know how to search
List.Any(s => string.Contains(s))
when I don't have a string variable already set. And ideally I'd just want to search each element of my list for a match without individually setting some temporary string variable.
Upvotes: 0
Views: 520
Reputation: 30464
So you have a sequence of DirectoryInfos
, and a sequence of strings
.
You want to filter the sequence of DirectoryInfos
in such a way that only those DirectoryInfos
that have a Name
that starts with at least one of the strings that is in your sequence of strings.
So if your sequence of strings contains "Foo", than your end result should at least contain all DirectoryInfos
whose Name
start with Foo
.
IEnumerable<string> strings = ...
IEnumerable<DirectoryInfo> directoryInfos = ...
var result = directoryInfos
.Where(directoryInfo => strings
.Any(str => directoryInfo.Name.StartsWitch(str));
In words:
From the sequence of all DirectoryInfos, keep only those DirectoryInfos, of which the name of this DirectoryInfo starts with at Any of the strings in the sequence of strings.
Upvotes: 1
Reputation: 641
.Where(x=> listOfStrings.Any(c=> x.Contains(c)))
is what you are looking for.
Upvotes: 1