2016-04-04 16 views
0

Belirli bir sütunda ToplamAğırlık miktarını saymaya çalışıyorum.Tablodaki belirli bir sütunun toplam sayımı

Aşağıdaki kodlamayı denedim, ancak yalnızca ilk satırın değerini elde ettim, diğerlerini değil.

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; 
} 

Yani benim soru: Ben tabloda Ağırlık sütunun toplam miktarını sayabilir nasıl?

cevap

3

Mevcut numarayı zaten aldığınız Weigth numarasına eklemek istersiniz, değil mi? Dahası, sadece - özelliğinin geçici olarak ayarlanması için QuoteItemSectionGroup'un yeni bir örneğini oluşturmanız gerekmeyecektir. x += 1 yılında

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 
} 

+= operatör sadece x = x + 1 için bir kısa yoldur. Linq Sum kullanılan yöntem

kullanılarak

Veya daha da basit

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

DÜZENLEME: cevap adam için

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

Teşekkür: nihayet bu hale böylece Üstelik size kod biraz kolaylaştırabilir. Ben C# teorisinin çoğuna bağlı değilim, ama bana '' '' '' çalışmalarından önce nasıl basit bir açıklama yapabilir misin? – CareTaker22

+0

Parlak! İkincisi harika. – CareTaker22

+1

@ CareTaker22 sözdizimi + = bir C# teorisi değildir, ancak çoğu dilde çalışır. Değişken = değişken + değer // için kısa bir kesim (varariable + = value) ' –

İlgili konular