Reputation: 1300
I'm trying to count the Total amount of Weight in a certain column.
I've tried the following coding, but I only seem to get the first row's value and not the rest.
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;
}
So my question is: How can I count the total amount of the Weight column in my table?
Upvotes: 0
Views: 427
Reputation: 37000
You obviously want to add the current number to the Weigth
you already obtained, don´t you? Furtheremore you won´t need to create a new instance of QuoteItemSectionGroup
only for the sake of setting its Weight
-property temporarily.
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
}
The +=
operator in x += 1
is simply a shortcut for x = x + 1
.
Or even simpler using Linq Sum
-method
var totalWeight = db.QuoteItemSectionGroups
.Where(x => x.QuoteItemId == item.Id)
.Sum(x => x.Weight);
EDIT: Furthermore you can simplify your code a bit so it finally becomes this:
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);
Upvotes: 3