Sunday, June 30, 2013

LINQ 10- Projection/Select- 1

Select method provides a way to transform each element to a desirable format.

Following code does nothing but gives a enumerable list of the source.

int[] numbers = new int[] { 1, 2, 3, 4, 5 };
IEnumerable<int> selected = numbers.Select(number => number);

 

Let try a simple transformation like getting the numbers doubled

int[] numbers = new int[] { 1, 2, 3, 4, 5 };
IEnumerable<int> selected = numbers.Select(number => number * 2);
foreach (var item in selected) {
    Console.WriteLine(item);
}
Console.ReadKey();

 

Above code returns a Enumerable set of integers with values doubled from the source.

So you will get result 2,4,6,8,10

 

Select method is declared in System.Linq.Enumerable class as

public static IEnumerable<TResult> Select<TSource, TResult>

(this IEnumerable<TSource> source,

Func<TSource, TResult> selector);

 

Here TSource is automatically identified from the input enumerable. As we are using Integer Array, TSource is identified as Integer.

 

TResult is identified from the delegate or lambda expression passed to the method. As we are returning just the doubled number TResult is also identified as Integer.

 

Consider the following example which returns a String.

int[] numbers = new int[] { 1, 2, 3, 4, 5 };
IEnumerable<String> selected = numbers.Select(number => (number * 2).ToString());
foreach (String item in selected) {
    Console.WriteLine(item);
}
Console.ReadKey();

 

As we are returning the string TResult is identified as String, hence the select returns IEnumerable<String>

No comments:

Post a Comment