LinQ: Join & GroupJoin 參考範例

Join 關聯明細, GroupJoin 分群計算, join + into, select + into

void Main()
{
	  Porduct[] productList = new Porduct[]
    {
        new Porduct {Id = 1, Name = "書籍"},
        new Porduct {Id = 2, Name = "玩具"}
    };

    Custom[] customList = new Custom[]
    {
        new Custom { ProductId = 1, FirstName = "Sandy",BuyCount = 3 },
        new Custom { ProductId = 1, FirstName = "Tom", BuyCount = 9 },
        new Custom { ProductId = 2, FirstName = "Vladimir", BuyCount = 8 },
        new Custom { ProductId = 2, FirstName = "Mikhail", BuyCount = 5 },
    };
		
	  // LinQ Join => 關聯明細 => 各產品被各個客人購買的數量
	  var result1 = 
	        from p in productList
				  join c in customList on p.Id equals c.ProductId
				  //select new {p,c}
				  select new {p.Name, c.FirstName, c.BuyCount };
				  
	  result1.Dump();
	
	  // LinQ GroupJoin => 分群計算 => 各產品被買最多的客人與數量
	  // GroupJoin = join + into
	  var qryTop1 = 
	        from p in productList
				  join c in customList on p.Id equals c.ProductId into g
				  //select new {p,g}
				  select new {p, top1 = g.OrderByDescending(c => c.BuyCount).First()};
				  
	  var top1Result = from tt in qryTop1
				   select new {
				   		tt.p.Name,
						  tt.top1.FirstName,
						  tt.top1.BuyCount
				   };
				   
	  top1Result.Dump();
	
	  // LinQ GroupJoin => 分群計算 => 各產品被買最多的客人與數量 --- 也可以這樣
	  // join + into => GroupJoin
	  // select + into => select into buffer to select more detail as result
	  var qryTop1TT = 
	        from p in productList
				  join c in customList on p.Id equals c.ProductId into g // GroupJoin
				  select new {p, top1 = g.OrderByDescending(c => c.BuyCount).First()} into tt // select into buffer
				  select new {
				   		tt.p.Name,
						  tt.top1.FirstName,
						  tt.top1.BuyCount
				   };
				   
	  qryTop1TT.Dump();	
	
}

class Porduct
{
    public int Id { get; set; }
    public string Name { get; set; }
}

class Custom
{
    public int ProductId { get; set; }
    public string FirstName { get; set; }
	  public int BuyCount {get; set; }
}

Last updated