Select. This C# method applies a method to elements. It is an elegant way to modify the elements in a collection such as an array.
C# method info. This method receives as a parameter an anonymous function—typically specified as a lambda expression. Other method syntax can be used as well.
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. We use Select on this array reference.
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
Type usage. 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.
Overload. The Select extension method also has an overload that receives a different form of anonymous mutator function as the argument.
Detail This version allows you to use the index of the element inside the body of the lambda expression.
Summary. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jul 1, 2021 (rewrite).