Smartssolutions

Wednesday, May 18, 2011

Join more than two collections using LINQ

Here is the code to join more that two collections using the Linq join clause

using System;
using System.Linq;

class Customer
{
    public int ID { get; set; }
    public string Name { get; set; }
}

class Order
{
    public int ID { get; set; }
    public string Product { get; set; }
}
class OrderDetails
{
    public int ID { get; set; }
    public int Quantity { get; set; }
}

class Program
{
    static void Main(string [] args)
    {
        // Example customers.
        var customers = new Customer[]
    {
        new Customer{ID = 5, Name = "Mahmoud"},
        new Customer{ID = 6, Name = "Salem"},
        new Customer{ID = 7, Name = "Monjya"},
        new Customer{ID = 8, Name = "Mehrez"}
    };

        // Example orders.
        var orders = new Order[]
    {
        new Order{ID = 5, Product = "Book"},
        new Order{ID = 6, Product = "Game"},
        new Order{ID = 7, Product = "Computer"},
        new Order{ID = 8, Product = "Shirt"}
    };
        //Example orders details
        var orderdetails = new OrderDetails[]
    {
        new OrderDetails{ID = 5, Quantity = 10},
        new OrderDetails{ID = 6, Quantity = 20},
        new OrderDetails{ID = 7, Quantity = 5},
        new OrderDetails{ID = 8, Quantity = 15}
    };
        var query = from c in customers
                    join o in orders on c.ID equals o.ID
                    join d in orderdetails on o.ID equals d.ID
                    select new
                    {
                        Name = c.Name,
                        Quantity = d.Quantity,
                        Product = o.Product
                    };

        // Display joined groups.
        foreach (var group in query)
        {
            Console.WriteLine("{0} bought {1} {2}s",group.Name,group.Quantity,group.Product);
        }
        Console.Read();
    }
}


No comments:

Post a Comment