[C#] Linq join 學習

摘要:[C#] Linq join 學習

static void Main(string[] args)
{
	List UnavailableList = new List 
	{ 
	new Product() { Description = "物品內容1", ItemID = 1, ItemName = "物品1", Price = 10 },
	new Product() { Description = "物品內容3", ItemID = 3, ItemName = "物品3", Price = 10 },
	new Product() { Description = "物品內容6", ItemID = 6, ItemName = "物品6", Price = 10 },
	new Product() { Description = "物品內容7", ItemID = 7, ItemName = "物品7", Price = 10 },
	new Product() { Description = "物品內容9", ItemID = 9, ItemName = "物品9", Price = 10 }
	};
	List CommodityList = new List 
	{ 
	new Product2() { ItemID = 1, ItemImage = "tw.yahoo.com.tw1" },
	new Product2() { ItemID = 7, ItemImage = "tw.yahoo.com.tw7" },
	new Product2() { ItemID = 3, ItemImage = "tw.yahoo.com.tw3" },
	new Product2() { ItemID = 9, ItemImage = "tw.yahoo.com.tw9" },
	new Product2() { ItemID = 6, ItemImage = "tw.yahoo.com.tw6" },
	};

var query1 =
	from x in CommodityList
	from y in UnavailableList
	where x.ItemID == y.ItemID
	select new
	{
	item1 = x,
	item2 = y
	};

var query2 = 
CommodityList.Join(
    UnavailableList, x => x.ItemID,y => y.ItemID,(x, y) => new { item1 = x, item2 = y }
                  );
​
			Console.WriteLine("query1:");
			foreach (var reslut in query1)
			{
				Console.WriteLine(reslut.item1.ItemImage + "" + reslut.item2.ItemName);
			}

			Console.WriteLine("\n");
			Console.WriteLine("query2:");
			foreach (var reslut in query2)
			{
				Console.WriteLine(reslut.item1.ItemImage + "" + reslut.item2.ItemName);
			}
			Console.WriteLine("\n query1和query2 的結果是一樣的");
		}
	}

參考資料:

LINQ Joins