C# Enumerable Where(IEnumerable, Func)

Description

Filters a sequence of values based on a predicate.

Syntax


public static IEnumerable<TSource> Where<TSource>(
  this IEnumerable<TSource> source,
  Func<TSource, bool> predicate
)

Parameters

  • TSource - The type of the elements of source.
  • source - An IEnumerable to filter.
  • predicate - A function to test each element for a condition.

Example

The following code example demonstrates how to use Where to filter a sequence.


/* www . j a  v  a  2s  . co  m*/
using System;
using System.Linq;
using System.Collections.Generic;
public class MainClass{
  public static void Main(String[] argv){  
     List<string> fruits =
         new List<string> { "apple", "orange", "blueberry", "grape", "strawberry" };

     IEnumerable<string> query = fruits.Where(fruit => fruit.Length < 6);

     foreach (string fruit in query)
     {
         Console.WriteLine(fruit);
     }

  }
}
    

The code above generates the following result.





















Home »
  C# Tutorial »
    System.Linq »




Enumerable