O'Reilly logo

LINQ Pocket Reference by Joseph Albahari, Ben Albahari

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required