How to perform Cross Join with Linq

Posted by berthin on Geeks with Blogs See other posts from Geeks with Blogs or by berthin
Published on Sat, 26 May 2012 09:44:16 GMT Indexed on 2012/05/30 16:43 UTC
Read the original article Hit count: 214

Filed under:

Cross join consists to perform a Cartesian product of two sets or sequences. The following example shows a simple Cartesian product of the sets A and B:

A (a1, a2)

B (b1, b2)

=> C (a1 b1,

           a1 b2,

           a2 b1,

           a2, b2 ) is the Cartesian product's result.

Linq to Sql allows using Cross join operations. Cross join is not equijoin, means that no predicate expression of equality in the Join clause of the query.

To define a cross join query, you can use multiple from clauses. Note that there's no explicit operator for the cross join.

In the following example, the query must join a sequence of Product with a sequence of Pricing Rules:

   1: //Fill the data source
   2: var products = new List<Product>
   3: {
   4:       new Product{ProductID="P01",ProductName="Amaryl"},
   5:       new Product {ProductID="P02", ProductName="acetaminophen"}                
   6: };
   7:  
   8: var pricingRules = new List<PricingRule>
   9: {
  10:       new PricingRule {RuleID="R_1", RuleType="Free goods"},
  11:       new PricingRule {RuleID="R_2", RuleType="Discount"},
  12:       new PricingRule {RuleID="R_3", RuleType="Discount"}
  13: };
  14:   
  15: //cross join query
  16: var crossJoin = from p in products
  17:                 from r in pricingRules
  18:                 select new { ProductID = p.ProductID, RuleID = r.RuleID };

 

Below the definition of the two entities using in the above example.

 

   1: public class Product
   2: {
   3:     public string ProductID { get; set; }
   4:     public string ProductName { get; set; }
   5: }
   1: public class PricingRule
   2: {
   3:     public string RuleID { get; set; }
   4:     public string RuleType { get; set; }
   5: }

 

Doing this:

   1: foreach (var result in crossJoin)
   2: {
   3:     Console.WriteLine("({0} , {1})", result.ProductID, result.RuleID);
   4: }

 

The output should be similar on this:

  ( P01   -    R_1 )

  ( P01   -    R_2 )

  ( P01   -    R_3 )

  ( P02   -    R_1 )

  ( P02   -    R_2 )

  ( P02   -    R_3)

Conclusion

Cross join operation is useful when performing a Cartesian product of two sequences object.

However, it can produce very large result sets that may caused a problem of performance. So use with precautions :)

© Geeks with Blogs or respective owner