具有相同商品ID的商品价格总和

时间:2015-04-19 16:06:03

标签: c# linq

我想要数据库表中具有相同项ID的所有行中的所有商品价格的总和。我的意思是当我从下拉列表中选择特定的项目ID时,结果应该是一个数字并自动将其放在文本框中

我怎样才能在linq中完成?

public double oIlstGetVouchersDetailjh(int nvoucherID)
{
    Training_sNairoukhEntities1 sNairoukhEntities1 = new Training_sNairoukhEntities1();
    double sum = (from Entity in sNairoukhEntities1.INV_InventoryItems
                                where Entity.ItemID == nvoucherID
                                select Entity.ItemPrice).sum();
    return sum;
}

public double oIlstGetVouchersDetailjh(int nvoucherID)
{
    Training_sNairoukhEntities1 sNairoukhEntities1 = new Training_sNairoukhEntities1();
    double olstInvoicesSrech = from Entity in sNairoukhEntities1.INV_InventoryItems
    group Entity by Entity.ItemID == nvoucherID into g
    select g.sum(Entity => Entity.ItemPrice);

    return olstInvoicesSrech;
}

但第二个查询给我这个msg无法隐式转换类型'System.Linq.IQueryable'为'double

1 个答案:

答案 0 :(得分:1)

在您的情况下,这将有效:

    Training_sNairoukhEntities1 sNairoukhEntities1 = new Training_sNairoukhEntities1();
    double sum = (from Entity in sNairoukhEntities1.INV_InventoryItems
                                where Entity.ItemID == nvoucherID
                                select Entity.ItemPrice).Sum(); // Change sum to Sum
    return sum;

这是一种更简单的方法:

sNairoukhEntities1.INV_InventoryItems.Where(item => item.ItemID == nvoucherID).Sum(item => item.ItemPrice);