Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trim() a list of strings using dynamic query language to produce a trimmed IQueryable<string>

Tags:

string

c#

trim

linq

Is this possible, or am I just trying to way overly shorten my code?

I thought it might be something like:

IQueryable<string> trimmedStrs = untrimmedStrsArr.AsQueryable<string>().All(s => s.Trim());

But that's no good :(

like image 874
Matt W Avatar asked Jul 12 '10 15:07

Matt W


3 Answers

I think you want just:

IEnumerable<string> trimmed = untrimmedStrsArr.Select(s => s.Trim());

If you have in-memory collection such as list or array, then you can work with them using LINQ methods for IEnumerable<T>, because these process data in memory. Queryable is useful when working with databases (e.g. using LINQ to SQL).

You can find a good documentation on various methods on MSDN. The following should explain why you need Select instead of All:

  • All - Determines whether all elements of a sequence satisfy a condition.
  • Select - Projects each element of a sequence into a new form.
like image 159
Tomas Petricek Avatar answered Oct 14 '22 11:10

Tomas Petricek


This one seemed to work for me:

IQueryable<string> trimmed = untrimmed.AsQueryable<string>().Select(m => m.Trim());
like image 3
Robaticus Avatar answered Oct 14 '22 10:10

Robaticus


All is not the right method to do this. It is a predicate, returning true if every item in the collection matches the condition you give in the parameter. Use

IQueryable<string> trimmedStrs = untrimmedStrsArr.AsQueryable<string>().Select(s => s.Trim()); 
like image 2
Jens Avatar answered Oct 14 '22 12:10

Jens