2

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 :-)

Matt
  • 24,106
  • 61
  • 180
  • 291

3 Answers3

3

Are you thinking of LINQ?

var textQuery = words.Select(word => word.ToLower());
Igor ostrovsky
  • 6,932
  • 2
  • 27
  • 28
  • Some days I am very very dumb :-) – Matt Sep 17 '09 at 23:09
  • This doesn't return a string however, but an `IEnumerable`. 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 Sep 17 '09 at 23:44
  • String.Join() was introduced in .NET 1.0, but generics only came in .NET 2.0. – Igor ostrovsky Sep 17 '09 at 23:53
  • I think Matt meant that the mapping function returns a string. – Igor ostrovsky Sep 17 '09 at 23:54
1

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
  • 362,140
  • 107
  • 528
  • 764
1

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
  • 13,614
  • 2
  • 46
  • 53