C# Enumerable Where(IEnumerable, Func)
Description
Filters a sequence of values based on a predicate. Each element's index is used in the logic of the predicate function.
Syntax
public static IEnumerable<TSource> Where<TSource>(
this IEnumerable<TSource> source,
Func<TSource, int, bool> predicate
)
Parameters
TSource
- The type of the elements of source.source
- An IEnumerableto filter. predicate
- A function to test each source element for a condition; the second parameter of the function represents the index of the source element.
Example
The following code example demonstrates how to use Where to filter a sequence based on a predicate that involves the index of each element.
/*w ww . j a v a2s. c o m*/
using System;
using System.Linq;
using System.Collections.Generic;
public class MainClass{
public static void Main(String[] argv){
int[] numbers = {15, 90, 85, 0, 30, 20, 40, 75 };
IEnumerable<int> query =
numbers.Where((number, index) => number <= index * 10);
foreach (int number in query)
{
Console.WriteLine(number);
}
}
}
The code above generates the following result.