Select - Transforming elements

Download c# eBook

Example

Select allows you to apply a transformation to every element in any data structure implementing IEnumerable.

Getting the first character of each string in the following list:

List<String> trees = new List<String>{ "Oak", "Birch", "Beech", "Elm", "Hazel", "Maple" };

Using regular (lambda) syntax

//The below select stament transforms each element in tree into its first character.
IEnumerable<String> initials = trees.Select(tree => tree.Substring(0, 1));
foreach (String initial in initials) {
    System.Console.WriteLine(initial);
}

Output:

O
B
B
E
H
M

Live Demo on .NET Fiddle

Using LINQ Query Syntax

initials = from tree in trees
           select tree.Substring(0, 1);

Stats

Contributors: 6
2016-08-12
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial: info@zzzprojects.com

Download eBook