TheDeveloperBlog.com


C# Where Method

Where filters elements from a collection. For example it can remove null or empty strings from an array in a single method call. The Where extension method in the C# language provides a simple way to accomplish this task.

Extension Method

Example. Let's look at an example program that calls the Where extension method from the System.Linq namespace two times with a different lambda expression each time. In the C# language, lambda expressions use the => operator.

Tip: This can be read as "goes to." Lambdas are normally parameters to methods that specify a behavior to be used in the method.

Next: This program uses Where to filter out null and empty strings in a declarative method call style.

C# program that uses Where method

using System;
using System.Linq;

class Program
{
    static void Main()
    {
	//
	// Example array that contains unwanted null and empty strings.
	//
	string[] array = { "dot", "", "net", null, null, "perls", null };
	//
	// Use Where method to remove null strings.
	//
	var result1 = array.Where(item => item != null);
	foreach (string value in result1)
	{
	    Console.WriteLine(value);
	}
	//
	// Use Where method to remove null and empty strings.
	//
	var result2 = array.Where(item => !string.IsNullOrEmpty(item));
	foreach (string value in result2)
	{
	    Console.WriteLine(value);
	}
    }
}

Output

dot         -- Begins output from first loop
	    -- Empty string included
net
perls
dot         -- Begins output from second loop
net
perls

The program calls the Where extension method twice. There is a string array that contains several null and empty strings mixed with the valid strings. The method is used to eliminate the null and empty strings in a single method call.

Note: The first Where call specifies that only non-null items should be kept. You can read "item => item != null" as "goes to non-null".

And: The second Where method call simply uses the string static method IsNullOrEmpty. It filters on that Boolean value.

Lambda Expression

Internals. Let's look at IL Disassembler and peek inside the Where extension method in the System.Linq namespace and System.Core.dll. Internally, Where uses the 'is' operator to search for the best implementation of the logic for the collection type.

IL Disassembler Tutorial

Opinion: I feel that Where imposes an unacceptable slowdown for numeric processing but is often acceptable for reference collections.

And: Evaluating the Where method may result in a new sequence being allocated on the managed heap.


Summary. We saw the Where extension method in the C# language and System.Linq namespace. This method provides a clear way to filter the elements in an IEnumerable collection with a single lambda expression.

Thus: The Where method allows you to write declarative rather than imperative code to do this.

ToArray