Reputation: 4421
I was wondering if it were possible to perform an operation on every element returned in a LINQ query at the same time as performing the query itself.
Example:
var files = Directory.EnumerateFiles(@"C:\etc", "*.*", SearchOption.AllDirectories)
.Where(s => (s.ToLower().EndsWith(".psd"))
&&
new FileInfo(s).Length > 500000);
finds all files within set criteria, but if I wanted to say trim "C:\" from each string that was returned, could I somehow say s = f(s) after the where clause or would this be a separate foreach each loop.
Thanks.
Upvotes: 0
Views: 96
Reputation: 106826
You want to do projection using the Select
clause:
var files = Directory.EnumerateFiles(@"C:\etc", "*.*", SearchOption.AllDirectories)
.Where(s => s.ToLower().EndsWith(".psd") && new FileInfo(s).Length > 500000)
.Select(s => s.Substring(3));
Upvotes: 1
Reputation: 269408
Yes, you can use the Select
method to do it:
var files = Directory.EnumerateFiles(/* ... */)
.Where(/* ... */)
.Select(s => s.StartsWith(@"C:\") ? s.Substring(3) : s);
Upvotes: 2
Reputation: 60694
After the Where statement, you can add this
.Select( s => s.Replace(@"C:\",""));
That will return the string with C:\ stripped.
Upvotes: 2