Gga
Gga

Reputation: 4421

Alter each value returned in a LINQ query at same time as query

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

Answers (3)

Martin Liversage
Martin Liversage

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

LukeH
LukeH

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

Øyvind Bråthen
Øyvind Bråthen

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

Related Questions