2016-04-04 38 views
0

我正在計數合計金額重量在某一列中。如何計算表中特定列的總數

我試過下面的代碼,但我似乎只得到第一行的值,而不是其餘。

int QuoteId = (from x in db.Quotes where x.Id != null orderby x.Id descending select x.Id).Take(1).SingleOrDefault(); 
var item = db.QuoteItems.Where(x => x.QuoteId == QuoteId).First(); 
QuoteItemSectionGroup quoteItemList = new QuoteItemSectionGroup(); 
foreach (var quoteItem in db.QuoteItemSectionGroups.Where(x => x.QuoteItemId == item.Id).ToList()) 
{ 
    var total = new QuoteItemSectionGroup 
    { 
     Weight = quoteItem.Weight 
    }; 
    quoteItemList.Weight = total.Weight; 
} 

所以我的問題是:我怎麼能算重量柱總量在我的表?

回答

3

您顯然想要將當前編號添加到已獲得的Weigth,不是嗎?此外,您不需要創建QuoteItemSectionGroup的新實例,僅僅是爲了臨時設置其Weight屬性。

foreach (var quoteItem in db.QuoteItemSectionGroups.Where(x => x.QuoteItemId == item.Id).ToList()) 
{ 
    quoteItemList.Weight += quoteItem.Weight; // pay attention on the + before the equality-character 
} 

+=的操作者在x += 1是簡單地爲x = x + 1的快捷方式。

或者也可以簡單使用LINQ Sum - 方法

var totalWeight = db.QuoteItemSectionGroups 
    .Where(x => x.QuoteItemId == item.Id) 
    .Sum(x => x.Weight); 

編輯:此外,你還可以簡化你的代碼了一點,所以它終於變成這樣:

var item = db.Quotes.Where(x => x.Id != null) 
    .OrderByDescending(x => x.Id) 
    .FirstOrDefault(); 
var totalWeight = db.QuoteItemSectionGroups 
    .Where(x => x.QuoteItemId == item.Id) 
    .Sum(x => x.Weight); 
+0

感謝您的回答的人。我對c#理論的大部分內容並不瞭解,但是你能否給我一個關於'='之前的'+'的基本解釋? – CareTaker22

+0

太棒了!第二個很棒。 – CareTaker22

+1

@ CareTaker22語法+ =不是c#的理論,但它適用於大多數語言。它是'variable = variable + value //(可變varariable + = value)'的捷徑 –

相關問題