views:

231

answers:

3

I am looking for a trick in newer dotnets where I can use inline functions that return a string value. Here's what I have:

var split = new[] { " " };
var words = SearchTextBox.Text.Trim().Split(
              split, 
              StringSplitOptions.RemoveEmptyEntries);
var textQuery = /*inlinefunction that operates on words array and returns a string.*/

I know I've seen this before maybe with chain methods or anonymous functions... I just can't recall if I imagined the whole thing or not :-)

+3  A: 

Are you thinking of LINQ?

var textQuery = words.Select(word => word.ToLower());
Igor ostrovsky
Some days I am very very dumb :-)
Matt
This doesn't return a string however, but an `IEnumerable<string>`. If you want a single string, you should combine the above answer with Joren's suggestion of using `String.Join`. Weird by the way that `Join` takes an array, anyone know why it doesn't take an `IEnumerable` or an `IList`?
JulianR
String.Join() was introduced in .NET 1.0, but generics only came in .NET 2.0.
Igor ostrovsky
I think Matt meant that the mapping function returns a string.
Igor ostrovsky
+1  A: 

Sounds like you're thinking about linq to objects, perhaps with a .First() at the end to get a string.

var textQuery = words.Where(w => w.Length > 5).First();

The key to making all the work are lamdba expression and IEnumerable<T> and it's associated extension methods. It's not limited to strings.

Joel Coehoorn
+1  A: 

To get a string out of a query (or any other IEnumerable), you can use String.Join. Example:

string result = String.Join(" ", textQuery.ToArray());

So use LINQ like the other answers suggest to operate on 'words', then use String.Join to recombine them into a string.

Joren