Filtering

Method

Description

SQL equivalents

Where

Returns a subset of elements that satisfy a given condition

WHERE

Take

Returns the first count elements, and discards the rest

WHERE ROW_NUMBER( )…orTOPn subquery

Skip

Ignores the first count elements, and returns the rest

WHERE ROW_NUMBER( )… or NOT IN (SELECT TOP n …)

TakeWhile

Emits elements from the input sequence until the predicate is true

Exception thrown

SkipWhile

Ignores elements from the input sequence until the predicate is true, and then emits the rest

Exception thrown

Distinct

Returns a collection that excludes duplicates

SELECT DISTINCT…

Note

The “SQL equivalents” column in the reference tables does not necessarily correspond to what an IQueryable implementation such as LINQ to SQL will produce. Rather, it indicates what you’d typically use to do the same job if you were writing the SQL query yourself. Where there is no simple translation, the column is left blank. Where there is no translation at all, the column reads “Exception thrown.”

Enumerable implementation code, when shown, excludes checking for null arguments, and indexing predicates.

With each of the filtering methods, you always end up with either the same number or fewer elements than you started with. You can never get more! The elements are also identical when they come out; they are not transformed in any way.

Where

Argument

Type

Source sequence

IEnumerable<TSource>

Predicate

TSource => bool or (TSource,int) => bool [a]

[a] Prohibited with LINQ to SQL

Comprehension ...

Get LINQ Pocket Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.