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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Jul 1, 2021 (rewrite).