■ Join(内部結合)
サンプル
商品クラス
class product
{
public int Id;
public string name;
}
// 値段クラス
class productPrice
{
public int Id;
public int price;
}
private void button2_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}
};
//var query = from x in productList // from 結合元のエイリアス名 in 結合元
// join y in productPriceList on x.Id equals y.Id // join 結合したいエイリアス名 in 結合したい対象 on 結合条件
// select new { Name = x.name, Price = y.price }; // select new { 表示させる項目 }
var query = productList // 結合元
.Join(productPriceList // .Join(結合したい対象
, (x) => x.Id // , (結合元エイリアス名) => 結合元の結合条件
, (y) => y.Id // , (結合したい対象のエイリアス名) => 結合したい対象の結合条件
, (x, y) => new // , (結合元エイリアス名, 結合したい対象のエイリアス名) => new
{
Name = x.name // 出力対象
, Price = y.price
});
string text = string.Empty;
foreach (var productData in query)
{
text += string.Format(" {0} : {1}", productData.Name, productData.Price);
}
label1.Text = text;
}
■ GroupJoin
サンプル
* 商品リストの商品番号と同じ商品番号の在庫は集約されて結合されますので、
商品番号ごとに在庫リストが作成可能になる
商品クラス
class product
{
public int Id;
public string name;
}
在庫クラス
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 = from x in productList
// join y in productStockList on x.Id equals y.Id into z
// select new
// {
// Name = x.name
// ,
// Stock = z.Sum(y => y.stock)
// };
var query = productList
.GroupJoin(productStockList
, (x) => x.Id
, (y) => y.Id
, (x, z) => new
{
Name = x.name
,
Stock = z.Sum(y => y.stock)
});
string text = string.Empty;
foreach (var productData in query)
{
text += string.Format(" {0} : {1}", productData.Name, productData.Stock);
}
label1.Text = text;
}