Search This Blog

Thursday, May 22, 2014

Join two tables Linq example C#

C# > LINQ > Join

Join is association of objects that share a common attribute.


Example:


DataTable dtOrder = new DataTable("order");
dtOrder.Columns.Add("id", Type.GetType("System.Int32"));
dtOrder.Columns.Add("customer", Type.GetType("System.String"));

DataRow dr = dtOrder.NewRow();
dr["id"] = 1;
dr["customer"] = "X Company";
dtOrder.Rows.Add(dr);

dr = dtOrder.NewRow();
dr["id"] = 2;
dr["customer"] = "Y Company";
dtOrder.Rows.Add(dr);

DataTable dtProduct = new DataTable("product");
dtProduct.Columns.Add("order_id", Type.GetType("System.Int32"));
dtProduct.Columns.Add("product", Type.GetType("System.String"));

dr = dtProduct.NewRow();
dr["order_id"] = 1;
dr["product"] = "Product 1";
dtProduct.Rows.Add(dr);

dr = dtProduct.NewRow();
dr["order_id"] = 1;
dr["product"] = "Product 2";
dtProduct.Rows.Add(dr);

var orderProducts = from order in dtOrder.AsEnumerable()
                    join product in dtProduct.AsEnumerable() on order.Field<int>("id")                               equals product.Field<int>("order_id")
                     select new
                                {
                                    OrderId = order.Field<int>("id"),
                                    Product = product.Field<string>("product")

                                };