HomeSearch

C# Where Keyword: Extension, From Where, Constraint

Use the Where extension method and the where keyword. Specify that certain element should be kept in a query.
Where. This is a keyword used inside queries. It is used in generic type constraints. And Where() is a method that filters elements from a collection.
We often use where in queries (with "from where"). As a type constraint, "where" is a less-common feature. The extension method Where() can filter an array with a lambda expression.Extension
Method example. This program calls the Where extension method from the System.Linq namespace 2 times with a different lambda expression each time. Lambda expressions use the => operator.Lambda

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

Array: We see a string array that contains some null and empty strings. The Where() eliminates the null and empty strings.

Note: The first Where call specifies that only non-null items should be kept. The second Where method call uses IsNullOrEmpty.

IsNullOrEmpty, IsNullOrWhiteSpace
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 net perls dot net perls
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

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.

Where, query. Where is not just a method. It is a contextual keyword in the C# language. This is the lowercase "where." It is part of a query expression (supported by System.Linq).LINQ
C# program that uses where using System; using System.Linq; class Program { static void Main() { int[] numbers = { 10, 20, 30, 40 }; // ... Filter numbers with where. var result = from number in numbers where number >= 30 select number; // ... Display results. foreach (int value in result) { Console.WriteLine(value); } } } Output 30 40
Where, constraint. Consider a generic type. We can use a constraint keyword to ensure that the type can only be used with certain types of elements. We use "where" to constrain a type.

Tip: Here we create a generic type called PageSet that can act on any element that implements the IPage interface.

Tip 2: We can use PageSet for any class that implements IPage—only one generic implementation is needed (this is a key advantage).

Also: More information is available about type constraints and generic types, and information about closed and open types.

Generic Class, Method
C# program that uses where constraint keyword using System; using System.Collections.Generic; /// <summary> /// PageSet (could be set of anything that implements IPage). /// </summary> class PageSet<T> where T : IPage { List<T> _pages = new List<T>(); public void Add(T page) { _pages.Add(page); } public void Render() { foreach (T page in _pages) { page.Render(); } } } /// <summary> /// IPage. /// </summary> interface IPage { void Render(); } /// <summary> /// ImagePage (implements IPage). /// </summary> class ImagePage : IPage { public void Render() { Console.WriteLine("Render ImagePage"); } } class Program { static void Main() { // ... Create a generic type with constraint. PageSet<ImagePage> pages = new PageSet<ImagePage>(); // ... Add an instance to the generic type. ImagePage image = new ImagePage(); pages.Add(image); // ... Use the generic type. pages.Render(); } } Output Render ImagePage
A key advantage. For type constraints the key advantage is the ability to reuse code when possible. We can share a single implementation, even if the type requires a certain interface.

Note: Thanks to Andrew Steitz for writing in with a correction to a program that uses the where keyword for a type constraint.

A summary. We saw the Where() method. This method filters the elements in an IEnumerable collection with a lambda expression. And we used where in queries and generics.
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
Home
Dot Net Perls