Select operator creates an output sequence of one type of element from an input sequence of another type of element.
The input element type and the output element type can be of different type.
There are two prototypes for this operator we will cover.
The First Select Prototype
public static IEnumerable<S> Select<T, S>(this IEnumerable<T> source,Func<T, S> selector);
This prototype of Select takes an input source sequence and a selector method delegate as input arguments.
It returns an object that, when enumerated, enumerates the input source sequence yielding a sequence of elements of type S.
T and S could be the same type or different types.
When calling Select, you pass a delegate to a selector method via the selector argument.
The selector method must accept a type T as input, where T is the type of elements contained in the input sequence.
It returns a type S element.
Select will call your selector method for each element in the input sequence, passing it the element.
The selector method selects the attributes or features of the input element you are interested in.
The selector method would create a new, possibly different typed element, which may be of an anonymous type, and return it.
The Second Select Prototype
public static IEnumerable<S> Select<T, S>(this IEnumerable<T> source,Func<T, int, S> selector);
The second Select operator can accept the zero-based index of the input element in the input sequence.
ArgumentNullException is thrown if any of the arguments are null.
The following code shows how to use the first prototype.
using System; using System.Linq; using System.Collections; using System.Collections.Generic; class Program//from ww w .j ava2 s .c o m { static void Main(string[] args) { string[] names = {"Python", "Java", "Javascript", "Bash", "C++", "Oracle"}; IEnumerable<int> nameLengths = names.Select(p => p.Length); foreach (int item in nameLengths) Console.WriteLine(item); } }
The code above are passing our selector method using a lambda expression.
The lambda expression will return the length of each element in the input sequence.
Our input types are strings, our output types are ints.