2016-04-04 21 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に明らかに現在の番号を追加したいと思いますか?さらに、Weightプロパティを一時的に設定するためにのみ、QuoteItemSectionGroupの新しいインスタンスを作成する必要はありません。 x += 1

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 = x + 1のショートカットです。

LINQの Sum -method

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

EDIT使用

あるいはさらに簡単:回答男のための

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

Brilliant! 2番目は素晴らしいです。 – CareTaker22

+1

@ CareTaker22構文+ =はC#の理論ではありませんが、ほとんどの言語で動作します。 'variable = variable + value //(可変変数+ =値)'のショートカットです。 –

関連する問題