Home
C#
Select Method
This page was last reviewed on Jul 1, 2021.
Dot Net Perls
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.
Array
String Literal
Then The Select method specifies a lambda expression, which applies the string instance method ToUpper to each element in the array.
Detail Each string element is modified to be its uppercase representation. The result of ToUpper is used.
String ToLower, ToUpper
Finally We use the foreach-loop. And the Console.WriteLine method prints the results to the screen.
foreach
Console.WriteLine
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.
Lambda
And This gives you the ability to apply the index to the result of the Select method and its mutation effects.
Overload
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.
SelectMany
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).
Home
Changes
© 2007-2024 Sam Allen.