Inline functions in dotNet 3.0+ with C#?

627 Views Asked by At

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

There are 3 best solutions below

4
Igor ostrovsky On BEST ANSWER

Are you thinking of LINQ?

var textQuery = words.Select(word => word.ToLower());
0
Joel Coehoorn On

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.

0
Joren On

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.