1. What is the GroupJoin operator?
2. What are the signatures of the GroupJoin operators?
3. What does happening when we use the GroupJoin operators?
The GroupJoin operator allows joining the elements from two sequences into one sequence.
There are two versions of the GroupJoin operator:
public static IEnumerable<TResult> GroupJoin<TOuter, TInner, TKey,
TResult>(
this IEnumerable<TOuter> outer,
IEnumerable<TInner> inner,
Func<TOuter, TKey> outerKeySelector,
Func<TInner, TKey> innerKeySelector,
Func<TOuter, IEnumerable<TInner>, TResult> resultSelector);
public static IEnumerable<TResult> GroupJoin<TOuter, TInner, TKey,
TResult>(
this IEnumerable<TOuter> outer,
IEnumerable<TInner> inner,
Func<TOuter, TKey> outerKeySelector,
Func<TInner, TKey> innerKeySelector,
Func<TOuter, IEnumerable<TInner>, TResult> resultSelector,
IEqualityComparer<TKey> comparer);
Example 1:
var expr = from p in Data.Products
join o in
(
from c in Data.Customers
from o in c.Orders
select o
)
on p.IdProduct equals o.IdProduct into orders
select new { p.IdProduct, Orders = orders };
foreach (var product in expr)
{
Trace.IndentLevel = 1;
Trace.WriteLine("ProductId: " + product.IdProduct);
Trace.Indent();
foreach (var order in product.Orders)
{
Trace.WriteLine("Order: " + order);
}
}
Output:
ProductId: 1
Order: 3 – False – January – 1
Order: 10 – False – July – 1
ProductId: 2
Order: 5 – True – May – 2
ProductId: 3
Order: 20 – True – December – 3
Order: 20 – True – December – 3
ProductId: 4
ProductId: 5
Order: 20 – False – July – 5
Order: 20 – False – July – 5
ProductId: 6
This is actually transformed by C# compiler into:
var expr = Data.Products
.GroupJoin(Data.Customers.SelectMany(c => c.Orders),
p => p.IdProduct,
o => o.IdProduct,
(p, orders) => new { p.IdProduct, Orders = orders });
When we use the GroupJoin operator it joins the inner sequence which is given as the inner parameter within outer sequence by keys which are given as selector functions and projects the result sequence according to given function. The only difference between the Join operator and the GroupJoin operator is that the resultSelector parameter must be IEnumerable<T> type.
The overloaded versions of the Join operator allow passing the custom comparer. By default the Join operator use the EqualityComparer<T>.