【C#】【Linq】LINQメソッド ~ 2つのキーでJoin編 ~

■ 2つのキーでJoin

サンプル

* 2つのキーでJoinするには、条件部分を『new { [条件1] , [条件2], ...}』とする
// 商品クラス
class product
{
    public int id;
    public int shopId;
    public string name;
}

// 値段クラス
class productPrice
{
    public int id;
    public int shopId;
    public int price;
}

// 店舗クラス
class shop
{
    public int shopId;
    public string shopName;
}

private void button1_Click(object sender, EventArgs e)
{
    product[] productList = {
                        new product() {id =1, shopId =1, name = "productA"}
                        , new product() {id =2, shopId =1, name = "productB"}
                        , new product() {id =3, shopId =3, name = "productC"}
                    };
    productPrice[] productPriceList = {
                        new productPrice() {id =1, shopId =1, price = 1980}
                        , new productPrice() {id =2, shopId =2, price = 2480}
                        , new productPrice() {id =3, shopId =3, price = 3980}
                    };
    shop[] shopList = {
                        new shop() {shopId =1, shopName = "shop1"}
                        , new shop() {shopId =2, shopName = "shop2"}
                        , new shop() {shopId =3, shopName = "shop3"}
                    };

    var query = productList // 結合元
        .Join(         // .Join(
        productPriceList // 結合したい対象
        , (x) => new { x.id , x.shopId }          // , (結合元エイリアス名) => 結合元の結合条件
        , (y) => new { y.id, y.shopId }           // , (結合したい対象のエイリアス名) => 結合したい対象の結合条件
        , (x, y) => new       // , (結合元エイリアス名, 結合したい対象のエイリアス名) => new
        {
            ShopId = x.shopId
            , Name = x.name       // 出力対象
            , Price = y.price
        })
        .Join(         // .Join(
        shopList // 結合したい対象
        , (x) => x.ShopId
        , (y) => y.shopId
        , (x, y) => new       // , (結合元エイリアス名, 結合したい対象のエイリアス名) => new
        {
            Name = x.Name       // 出力対象
            , Price = x.Price
            , ShopName = y.shopName
        });

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

    label1.Text = text;

}