Join operator

            1. What is the Join operator?

            2. What are the signatures of the Join operators?

            3. What does happening when we use the Join operators?

The Join operator allows joining the elements from two sequences into one sequence. There are four versions of the Join operator:

public static IEnumerable<TResult> Join<TOuter, TInner, TKey, TResult>(

    this IEnumerable<TOuter> outer,

    IEnumerable<TInner> inner,

    Func<TOuter, TKey> outerKeySelector,

    Func<TInner, TKey> innerKeySelector,

    Func<TOuter, TInner, TResult> resultSelector);

 

public static IEnumerable<TResult> Join<TOuter, TInner, TKey, TResult>(

    this IEnumerable<TOuter> outer,

    IEnumerable<TInner> inner,

    Func<TOuter, TKey> outerKeySelector,

    Func<TInner, TKey> innerKeySelector,

    Func<TOuter, TInner, TResult> resultSelector,

    IEqualityComparer<TKey> comparer);

 

Example 1:

            var expr = from c in Data.Customers

                       from o in c.Orders

                       join p in Data.Products on o.IdProduct equals p.IdProduct

                       select new { o.Month, o.Shipped, p.IdProduct, p.Price };

 

Output:

 

{ Month = January, Shipped = False, IdProduct = 1, Price = 10 }

{ Month = May, Shipped = True, IdProduct = 2, Price = 20 }

{ Month = July, Shipped = False, IdProduct = 1, Price = 10 }

{ Month = December, Shipped = True, IdProduct = 3, Price = 30 }

{ Month = December, Shipped = True, IdProduct = 3, Price = 30 }

{ Month = July, Shipped = False, IdProduct = 5, Price = 50 }

{ Month = July, Shipped = False, IdProduct = 5, Price = 50 }

 

This is actually transformed by C# compiler into:

 

            var expr = Data.Customers

                        .SelectMany(c => c.Orders)

                        .Join(Data.Products,

                                o => o.IdProduct,

                                p => p.IdProduct,

                                (o, p) => new { o.Month, o.Shipped, p.IdProduct, p.Price });

 

When we use the Join 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 overloaded versions of the Join operator allow passing the custom comparer. By default the Join operator use the EqualityComparer<T>.

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s