Linq将值与同一个表分开并绑定到gridview

时间:2013-12-26 11:24:04

标签: c# linq entity-framework linq-to-sql linq-to-entities

我有以下表格:

      ID    |  Type |   Desc    | Amount
  ---------------------------------------
  Stationery|  Pen  |  Red Pen  |  1.00
  Stationery|  Pen  |  Blue Pen |  1.10
  Stationery| Ruler |  A Ruler  |  1.50
  Stationery| Ruler |  B Ruler  |  1.40

我想获得不同类型的总金额。 Pen的总和是2.10,而尺子是2.90。我怎么做到这一点?我尝试使用“分组依据”。这是我的疑问:

From c In DB.Shop 
Group By c.Type 
Into TotalAmount=Sum(c.Amount) Select Type,TotalAmount

然后我将选择值并绑定到gridview。将数据绑定到gridview对我来说不是问题。 gridview的预期结果如下:

     ID    |  PenAmount | RulerAmount
-------------------------------------
 Stationery|    2.10    |   2.90 

请帮忙。感谢

2 个答案:

答案 0 :(得分:0)

以下是一个例子:

var query =
    (from c in DB.Shop
    group c by c.Type
    into grp
    select new
    {
        type = grp.Key,
        value = grp.Sum(g => g.Amount)
    });

grp.Key将包含c.Type,因为Type属性构造了分组。您可能需要进行一些调整才能获得准确的工作代码,因为我没有对上面的linq进行测试,而且我也不确切知道您的对象模型。

答案 1 :(得分:0)

试试这个

var query =
    (from c in DB.Shop
    group c by c.Type
    into grp
    select new
    {
        Type= g.Key,
        PenAmount = g.Where(c => c.Type=="Pen").Sum(c => c.Amount),
        RulerAmount= g.Where(c => c.Type=="Ruler").Sum(c => c.Amount),

    });