Select
The C# Select()
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. Other method syntax can be used as well.
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. We use Select()
on this array reference.
Select()
method specifies a lambda expression, which applies the string
instance method ToUpper
to each element in the array.string
element is modified to be its uppercase representation. The result of ToUpper
is used.foreach
-loop. And the Console.WriteLine
method prints the results to the screen.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); } } }CAT DOG MOUSE
The Select()
method can be used on many different collection types. You can experiment with it on List
types, and other array types, and even results from other query expressions.
The Select()
extension method also has an overload that receives a different form of anonymous mutator function as the argument.
Select()
method and its mutation effects.We looked at the simplest form of the Select()
extension method. The name "select" is possibly confusing, as the method provides a mutation function, not just a selection function.