[LINQ Operators] Where

The “Where” operator filters a sequence based on a predicate (condition).

 

1. Sample Data Object

To test examples, you need to include the <data classes> in your project.

 

2. “Where” operator

  • Deferred operator
  • Purpose: Filtering / Restriction

 

3. Prototypes

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

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

You need a predicate delete which gets each element and returns “true” or “false”. The second prototype has another integer input argument; which is an index number (zero-based) for the element from the input sequence.

 

4. Example 1 (Standard Operator)

var emps = Employee.GetEmployees();

var empSmiths
  = emps.Where(e => e.Name.Contains("Smith"));

foreach (Employee e in empSmiths)
{
  Console.WriteLine($"{e.Id}: {e.Name}");
}

 

5. Example 2 (Query Expression)

var emps = Employee.GetEmployees();

var empSmiths
  = from e in emps
    where (e.Name.Contains("Smith"))
    select e;

foreach (Employee e in empSmiths)
{
  Console.WriteLine($"{e.Id}: {e.Name}");
}

 

6. Example 3 (Standard Operator): with an index number

var emps = Employee.GetEmployees();

var empSmiths
  = emps.Where((e,i) => (i & 1) == 1); // odd index

foreach (Employee e in empSmiths)
{
  Console.WriteLine($"{e.Id}: {e.Name}");
}

 

7. Example 4 (Query Expression): with an index number

There is no direct translation from “Func(T, int, bool)” to a query expression. You can work around this like the following but I do not recommend to do it.

var emps = Employee.GetEmployees();

var empSmiths
  = from emp in emps.Select( (e, i) => new { e, i } )
    where ((emp.i & 1) == 1) // odd index
    select emp.e;

foreach (Employee e in empSmiths)
{
  Console.WriteLine($"{e.Id}: {e.Name}");
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s