Projecting

Method

Description

SQL equivalents

Select

Transforms each input element with the given lambda expression

SELECT

SelectMany

Transforms each input element, then flattens and concatenates the resultant subsequences

INNER JOIN, LEFT OUTER JOIN, CROSS JOIN

Note

For LINQ to SQL queries, Select and SelectMany are the most versatile joining constructs; for local queries, Join and GroupJoin are the most efficient joining constructs.

Select

Argument

Type

Source sequence

IEnumerable<TSource>

Result selector

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

[a] Prohibited with LINQ to SQL

*Comprehension syntax

	select projection-expression

Overview

With Select, you always get the same number of elements that you started with. Each element, however, can be transformed in any manner by the lambda function.

The following selects the names of all fonts installed on the computer (from System.Drawing):

	IEnumerable<string> query =
	  from f in FontFamily.Families
	  select f.Name;

	foreach (string name in query) Console.WriteLine (name);

In this example, the select clause converts a FontFamily object to its name. Here’s the lambda equivalent:

	IEnumerable<string> query =
	  FontFamily.Families.Select (f => f.Name);

Select statements are often used to project into anonymous types:

	var query =
	  from f in FontFamily.Families
	  select new
	  {
	    f.Name,
	    LineSpacing = f.GetLineSpacing (FontStyle.Bold)
	};

A projection with no transformation is sometimes used in comprehension queries to satisfy the requirement that the query ...

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.