【C#】Linqメソッド ~ 外部結合 (Left Outer Join) 編 ~

■左外部結合 (Left Outer Join)

サンプル

class product
{
    public int Id;
    public string name;
}

class productPrice
{
    public int Id;
    public int price;
}

class productStock
{
    public int Id;
    public int stock;
}
private void button6_Click(object sender, EventArgs e)
{
    product[] productList = {
                                new product() {Id =1, name = "productA"}
                                , new product() {Id =2, name = "productB"}
                                , new product() {Id =3, name = "productC"}
                            };
    productPrice[] productPriceList = {
                                new productPrice() {Id =1, price = 1980}
                                , new productPrice() {Id =2, price = 2480}
                                , new productPrice() {Id =3, price = 3980}
                            };
    productStock[] productStockList = {
                                new productStock() {Id =1, stock = 30}
                                , new productStock() {Id =1, stock = 20}
                                , new productStock() {Id =3, stock = 15}
                            };

    var query = productList
        .GroupJoin(productPriceList,
        a => a.Id,
        b => b.Id,
        (a, b) => new
        {
            temp1 = a,
            temp2 = b
        })
        .SelectMany(
        c => c.temp2.DefaultIfEmpty(new productPrice() { price = 0 }),
        (a, b) => new
        {
            Id = a.temp1.Id,
            Name = a.temp1.name,
            Price = b.price
        })
        .GroupJoin(productStockList,
        a => a.Id,
        b => b.Id,
        (a, b) => new
        {
            temp1 = a,
            temp2 = b
        })
        .SelectMany(
        c => c.temp2.DefaultIfEmpty(new productStock() { stock = 0}),
        (a, b) => new
        {
            Id = a.temp1.Id,
            Name = a.temp1.Name,
            Price = a.temp1.Price,
            Stock = b.stock
        }
        );


    string text = string.Empty;
    foreach (var productData in query)
    {
        text += string.Format(" {0} : {1} | {2} | {3}\n"
            , productData.Id, productData.Name, productData.Price, productData.Stock);
    }

    label1.Text = text;
}