Joins and their corresponding LINQ Query Extension methods
Type of join
|
Query extension
method
|
Example
|
Example Result
(By enumerating
through the query variable and displaying the details on console)
|
Inner Join
|
Join
|
var makes = new
string[] { "Audi", "BMW", "Ford",
"Mazda", "VW" };
var cars =
GetCars();
var query =
makes.Join(cars,
make => make,
car => car.Make,
(make, innerCar)
=> new { Make = make, Car = innerCar });
|
Make: Audi,
Car:ABC456 Audi TT
Make: BMW,
Car:DEF123 BMW Z-3
Make: Ford,
Car:ABC123 Ford F-250
Make: Ford,
Car:DEF456 Ford F-150
Make: VW,
Car:HIJ123 VW Bug
|
Left Outer Join
|
GroupJoin
|
var makes = new
string[] { "Audi", "BMW", "Ford",
"Mazda", "VW" };
var cars =
GetCars();
var query =
makes.GroupJoin(cars,
make => make,
car => car.Make,
(make, innerCars)
=> new { Make = make, Cars = innerCars });
|
Make: Audi
Car VIN:ABC456,
Model:TT
Make: BMW
Car VIN:DEF123,
Model:Z-3
Make: Ford
Car VIN:ABC123,
Model:F-250
Car VIN:DEF456,
Model:F-150
Make: Mazda
Make: VW
Car VIN:HIJ123,
Model:Bug
|
Cross Join
(Cartesian product)
|
SelectMany
|
var repairs = new
List<Tuple<string, List<string>>>
{
Tuple.Create("ABC123",
new
List<string>{"Rotate Tires","Change oil"}),
Tuple.Create("DEF123",
new
List<string>{"Fix Flat","Wash Vehicle"}),
Tuple.Create("ABC456",
new
List<string>{"Alignment","Vacuum",
"Wax"}),
Tuple.Create("HIJ123",
new
List<string>{"Spark plugs","Air filter"}),
Tuple.Create("DEF456",
new
List<string>{"Wiper blades","PVC valve"}),
};
var query =
repairs.SelectMany(t =>
t.Item2.Select(r
=> new { VIN = t.Item1, Repair = r }));
|
VIN:ABC123
Repair:Rotate Tires
VIN:ABC123
Repair:Change oil
VIN:DEF123
Repair:Fix Flat
VIN:DEF123
Repair:Wash Vehicle
VIN:ABC456
Repair:Alignment
VIN:ABC456
Repair:Vacuum
VIN:ABC456
Repair:Wax
VIN:HIJ123
Repair:Spark plugs
VIN:HIJ123
Repair:Air filter
VIN:DEF456
Repair:Wiper blades
VIN:DEF456
Repair:PVC valve
|
Extension method
syntax - [source collection].[extension method].[extension method]…;
PS: Please comment if this served your purpose by any chance. Happy coding :)
PS: Please comment if this served your purpose by any chance. Happy coding :)
No comments:
Post a Comment
Please help to make the post more helpful with your comments.