Veverke
Veverke

Reputation: 11358

Linq Select and SelectMany performing joins

C# 6.0 in a Nutshell by Joseph Albahari and Ben Albahari (O’Reilly).

Copyright 2016 Joseph Albahari and Ben Albahari, 978-1-491-92706-9.

Exposes, in chapter 9, on Linq Operators. For each operation, such as filtering, projecting, joining, etc, it lists the extension methods available in System.Linq to perform the operation in question.

At page 394, it deals with projecting:

Projecting (Input: IEnumerable<TSource> → Output: IEnumerable<TResult>)

Transforms each element with a lambda function. SelectMany flattens nested sequences; Select and SelectMany perform inner joins, left outer joins, cross joins, and non-equi joins with LINQ to SQL and EF:

Linq API: Select, SelectMany

Intuitively, its much easier to see how SelectMany is equivalent to joining in relational databases, but what about Select alone ? I'm not sure I see how Select alone can do any sort of joining.

Could it be that the only case where Select does something equivalent to a join is like

IEnumerable<TInput> input = ...

input.Select(new [SomeType] { a = input.a + c, b = input.a + d }; 

It could be said then that this Projection is implicitly defining a relation between type TInput and SomeType, and thus representing a join ? Am I right ?

Upvotes: 1

Views: 1364

Answers (1)

Zein Makki
Zein Makki

Reputation: 30032

A Simple example:

context.Students.where(x=> x.StudentID == 1).Select(x=> x.Department).FirstOrDefault();

is Equivelant to:

SELECT TOP 1 D.* FROM Student S 
INNER JOIN Department D
ON S.DepartmentID = D.DepartmentID
WHERE S.StudentID = 1

Basically using Select in combination with navigation properties may result in a JOIN at some point. In the above Linq Query you're selecting the Department for that Student with ID == 1.

I'm not 100 % sure if that provider would generate an INNER or LEFT join, but the point is that a JOIN operation is resulted from a Select method.

Upvotes: 3

Related Questions