如何计算表中特定列的总数

时间:2016-04-04 12:58:53

标签: c# .net linq count

我正在尝试计算某列中总重重量金额。

我尝试过以下编码,但我似乎只得到第一行的值,而不是其余的。

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

所以我的问题是:如何计算表格中 Weight 列的总数?

1 个答案:

答案 0 :(得分: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);