【发布时间】:2015-03-24 05:47:52
【问题描述】:
我在数据库中有一个包含动态记录的表。我使用静态数据(商品)得到了正确的结果,但我需要使用动态数据得到结果。
数据库表是:
Id Month Commodity Amount
----------------------------
1 May wheat 100
2 May rice 200
3 June wheat 400
4 July maize 100
5 June wheat 100
我的结果:
Month wheat rice maize
--------------------------------
May 100 200
June 500
July 100
我的aspx代码:
<asp:GridView ID="grdData" runat="server">
</asp:GridView>
和 aspx.cs 代码
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
getdata();
}
}
public void getdata()
{
using (GridFormatEntities context = new GridFormatEntities())
{
var result = (from r in context.tbl_Commodity
select new
{
Id = r.Id,
Month = r.Month,
Commodity = r.Commodity,
Amount = r.Amount
})
.GroupBy(r => r.Month)
.Select(r => new
{
Month = r.Key,
Wheat = r.Where(x => x.Commodity == "Wheat").Sum(x => x.Amount),
Rice = r.Where(x => x.Commodity == "Rice").Sum(x => x.Amount),
maize= r.Where(x => x.Commodity == "maize").Sum(x => x.Amount),
}).ToList();
grdData.DataSource = result;
grdData.DataBind();
}
}
在上面的查询中,它是静态的(小麦、大米和玉米),但我动态需要这些商品...请帮助我如何使用动态数据(商品)来管理它们。
【问题讨论】:
-
第一个商品数量,使用 rows.count 或 count(sql),只需编写一个循环 for(i=0;i
-
如何在 linq 查询中使用 for 循环?
标签: c# asp.net gridview entity-framework-5