C# Enumerable Select(IEnumerable, Func)
Description
Projects each element of a sequence into a new form by incorporating the element's index.
Syntax
public static IEnumerable<TResult> Select<TSource, TResult>(
this IEnumerable<TSource> source,
Func<TSource, int, TResult> selector
)
Parameters
TSource
- The type of the elements of source.TResult
- The type of the value returned by selector.source
- A sequence of values to invoke a transform function on.selector
- A transform function to apply to each source element; the second parameter of the function represents the index of the source element.
Example
The following code example demonstrates how to use Select to project over a sequence of values and use the index of each element.
/* w ww. ja v a 2 s . c om*/
using System;
using System.Linq;
using System.Collections.Generic;
public class MainClass{
public static void Main(String[] argv){
string[] myData = { "Java", "Java XML", };
var query = myData.Select((fruit, index) =>
new { index, str = fruit.Substring(0, index) });
foreach (var obj in query)
{
Console.WriteLine("{0}", obj);
}
}
}
The code above generates the following result.