HomeSearch

C# Select Method (Use Lambda to Modify Elements)

This C# program uses the Select extension from the System.Linq namespace. Select calls a lambda to modify each element.

Select.

This method applies a method to elements. It is an elegant way to modify the elements in a collection such as an array. This method receives as a parameter an anonymous function—typically specified as a lambda expression.

Example.

Let's look at a program where the Select extension method is applied to a string array. A local variable of array type is allocated and three string literals are used. We use Select on this array reference.String ArrayString Literal

Then: The Select method specifies a lambda expression, which applies the string instance method ToUpper to each element in the array.

Uppercase: Each string element is modified to be its uppercase representation. The result of ToUpper is used.

ToLower

Finally: We use the foreach-loop. And the Console.WriteLine method prints the results to the screen.

ForeachConsole.WriteLine
C# program that uses Select method using System; using System.Linq; class Program { static void Main() { // An input data array. string[] array = { "cat", "dog", "mouse" }; // Apply a transformation lambda expression to each element. // ... The Select method changes each element in the result. var result = array.Select(element => element.ToUpper()); // Display the result. foreach (string value in result) { Console.WriteLine(value); } } } Output CAT DOG MOUSE

The Select method

can definitely be used on many different collection types, not just an array or a string type array. You can experiment with it on List types, and other array types, and even results from other query expressions.

Lambda expression syntax

is somewhat tricky. The "=>" in this context does not specify a comparison, but rather can be read as "goes to." It separates the arguments from the body of the method.

Tip: A lambda expression is the same as a regular method conceptually, but written in a more condensed syntax.

Overload.

The Select extension method also has an overload that receives a different form of anonymous mutator function as the argument. This version allows you to use the index of the element inside the body of the lambda expression.

And: This gives you the ability to apply the index to the result of the Select method and its mutation effects.

Overload Method

Summary.

We looked at the simplest form of the Select extension method from the System.Linq namespace in the C# language. The name "select" is possibly confusing, as the method actually provides a mutation function, not just a selection function.SelectMany
Home
Dot Net Perls
© 2007-2019 Sam Allen. All rights reserved. Written by Sam Allen, info@dotnetperls.com.