Reputation: 37
I know why the following code does not work when the "excl" list has more than one string. It's because as each string is evaluated in the lambda it now includes whatever was excluded in the previous iteration of "x." My question is, how do I get it to properly exclude multiple items in the final result?
var di = new DirectoryInfo(@"\\192.168.1.10\e$");
var excl = new List<string>();
excl.Add("Temp");
excl.Add("VSS");
var dirs = from d in di.GetDirectories()
where (d.Attributes & FileAttributes.System) != FileAttributes.System
select d;
dirs = excl
.SelectMany(x => from d in dirs
where !d.FullName.ToLowerInvariant().Contains(x.ToLowerInvariant())
select d)
.Distinct().ToArray();
Upvotes: 2
Views: 949
Reputation: 160852
Something like this should work:
var di = new DirectoryInfo(@"\\192.168.1.10\e$");
var dirs = di.EnumerateDirectories()
.Where(d=> !excl.Any(e=>d.FullName.ToLowerInvariant().Contains(e)));
I would think about your exclusion criteria though - do you want to exclude every directory that contains your exclusion string or just directories whose names match a exclusion item?
Also to make this faster you can create a HashSet<string>
from your exclusion list and use that.
Upvotes: 2
Reputation: 51319
What it seems like you want to do is this (nested iteration):
dirs = dirs.Where(d => !excl.Any(x => d.FullName.ToLowerInvariant().Contains(x.ToLowerInvariant())))
.Distinct().ToArray();
Upvotes: 3