2011-07-07 58 views
9

我遇到了麻煩。我無法理解堆棧溢出對此的現有答案,並且對於LINQ to SQL來說,我自己也無法解決這個問題。將簡單的SQL組轉換爲LINQ到SQL

看到這個SQL:

select p.Name as ProductName, SUM(o.NumberOf) as TotalOrdered from [Order] o 
    join [Product] p on o.ProductId = p.Id 
    group by p.Name 

返回一個漂亮的2列的表在左側產品名稱和總數已在右列已下令(在所有訂單)產品。我如何在LINQ to SQL中複製這個?

這裏是我到目前爲止有:

var ctx = new DataClasses1DataContext(); 
var totalProducts = (from o in ctx.Orders 
        join p in ctx.Products on o.ProductId equals p.Id 
        select new { p.Name, o.NumberOf }) 
    .GroupBy(t => t.Name) 
    .Select(g => g.Key, ...); 

什麼在去...?

回答

25

它看起來像你對我想:

.Select(g => new { ProductName = g.Key, TotalOrdered = g.Sum(x => x.NumberOf) }) 

您可以作爲做你的整個查詢一個查詢表達式或根本不使用查詢表達式:

var totalProducts = ctx.Orders 
         .Join(ctx.Products, o => o.ProductId, p => p.Id, 
          (o, p) => new { p.Name, o.NumberOf }) 
         .GroupBy(t => t.Name, 
           pair => pair.Name, // Key selector 
           pair => pair.NumberOf, // Element selector 
           (key, numbers) => new { 
            ProductName = key, 
            TotalOrdered = numbers.Sum()) 
           }); 

或者:

var totalProdcuts = from o in ctx.Orders 
        join p in ctx.Products on o.ProductId equals p.Id 
        group o.NumberOf by p.Name into g 
        select new { ProductName = g.Key, TotalOrdered = g.Sum() }; 
+0

這是正確的。剛剛檢查過。感謝您在我腦海中死去的時刻幫助我。 – Lisa

+1

@Lisa:好的 - 會進一步編輯... –

+0

爲了響應您的更新,我已經按名稱分組。 – Lisa

2
TotalOrdered = g.Sum(o => o.NumberOf) 

化妝用的上面....比語句可能是

select new { ProductName= g.Key, TotalOrdered = g.Sum(o => o.NumberOf) }; 

var query = from o in ctx.Orders 
      join p in ctx.Products on 
      o.ProductId equals p.Id 
      group o by new { p.Name, o.NumberOf } into g 
      select new { ProductName= g.Key, TotalOrdered = g.Sum(o => o.NumberOf) }; 
+0

我明白如何獲得總和。令我困惑的是如何將它融入投影。 – Lisa

+0

@Lisa - 立即嘗試 –

+0

是的,這也是完美的。我認爲這是我一開始就在尋找的東西。它比LINQ-to-SQL和Linq擴展組合更加優雅。 – Lisa

0

只需粘貼此位置的情況下,它有助於瞭解如何可以通過羣組加入方法來實現:

var totalProducts = ctx.Products.GroupJoin(ctx.Orders, 
    outerKeySelProduct => outerKeySelProduct.Id, 
    innerKeySelOrder => innerKeySelOrder.ProductId, 
    (outerKeySelProduct, innerKeySelOrder) => new 
    { 
     ProductName = outerKeySelProduct.Name, 
     TotalOrdered = innerKeySelOrder.Select(n => n.NumberOf).Sum() 
    }); 

高興,如果能夠提高它進行編輯。