C# Select

Select method call

Select applies a method to every element. It is an elegant way to mutate the elements in a collection such as an array. This method receives as a parameter an anonymous function—typically specified as a lambda expression or delegate.

Lambda Expression

Example

This section provides information

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

The Select method then specifies a lambda expression, which applies the string instance method ToUpper to each element in the array. Each string element is changed to its uppercase representation.

ToUpper

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
Lambda expression syntax

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

Programming tip

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

C#: LINQ