[英]Asp.Net Foreach and groupby
I want get all my records and group by ProgramId
and then view this. 我想获取所有记录并按
ProgramId
分组,然后查看此内容。
var userProgramsStats = (from a in db.Statistics where a.UserId == login.GetUserObject().UserId select a)
.GroupBy(a => a.ProgramId);
ViewBag.userProgramsStats = userProgramsStats
And in template: 并在模板中:
@foreach (var item in ViewBag.UserProgramsStats)
{
@item.MoneyRate
}
Unfortunately I see this error: 不幸的是,我看到此错误:
An unhandled exception has occurred: 'object' does not contain a definition for 'MoneyRate'
发生未处理的异常:“对象”不包含“ MoneyRate”的定义
I must get all records where userid, and then groupby programid
and sum one column MoneyRate
. 我必须把所有记录其中userid,然后GROUPBY
programid
,总结一列MoneyRate
。 Then I want use like this: 然后我想这样使用:
@item.MoneyRate<br /> // sum MoneyRate
@item.OthercolumnNormal
Your error is due to the wrong type of object of your data item
: While processing the foreach, the type of your data is not recognized. 您的错误是由于数据
item
的对象类型错误引起的:在处理foreach时,无法识别您的数据类型。
You should specify a Data Model : 您应该指定一个数据模型:
public class UserStat {
public double MoneyRate { get; set; }
public string ColumnNormal {get; set;}
public UserStat() { }
public UserStat(double moneyRate, string columnNormal)
{
MoneyRate = moneyRate;
ColumnNormal = columnNormal;
}
}
Then in your template, you should : 然后在模板中,您应该:
@foreach (UserStat item in ViewBag.UserProgramsStats)
{
@item.MoneyRate
}
You might also do something like this: 您可能还会执行以下操作:
@foreach (dynamic item in ViewBag.UserProgramsStats)
{
@item.MoneyRate
}
Using the dynamic
keyword will evaluate if the property exist at run time. 使用
dynamic
关键字将评估该属性在运行时是否存在。
You are getting a type error because the type of userProgramsStats does not contain a property MoneyRate. 您收到类型错误,因为userProgramsStats的类型不包含属性MoneyRate。
You say you want to sum the MoneyRate column, to do this you need to project the grouped result into a new type. 您说要对MoneyRate列求和,为此,您需要将分组结果投影到新类型中。
Taking your existing query I've added a select statement onto the end of it that projects into a new anonymous type the programId and the sum of the MoneyRate column for each programId. 考虑到您现有的查询,我在其末尾添加了一条select语句,该语句投影到一个新的匿名类型中,即programId和每个programId的MoneyRate列的总和。
var result = (from a in db.Statistics where a.UserId login.GetUserObject().UserId select a)
.GroupBy(a => a.programid)
.Select(group => new { MoneyRateSum = group.Sum(i => i.MoneyRate), ProgramId = group.Key });
For more information on projecting and anonymous types read https://msdn.microsoft.com/en-us/library/bb397914.aspx . 有关投影类型和匿名类型的更多信息,请阅读https://msdn.microsoft.com/zh-cn/library/bb397914.aspx 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.