我有一个相当简单的模型:
public class Delivery
{
public int DeliveryId { get; set; }
public int OverId { get; set; }
public int Ball { get; set; }
public int Runs { get; set; }
public Player Player { get; set; }
}
我想做的就是将我的Delivery对象集合按Player分组,这样我就可以在MVC3视图中对结果进行一些统计计算。
我差不多了,但是在L2S查询和我的模型绑定声明之间,我只是不能让两者结婚。
这样做几乎可行:
var batting = from d in deliveries
where d.Over.IsBatting == true
group d by d.Player into player
select player;
return View(batting);
但视图绑定是一团糟。 有点帮助?
编辑: 这是我的观点:
@model IEnumerable<IGrouping<Cricket.Models.Player, Cricket.Models.Delivery>>
@{
ViewBag.Title = "Batting";
}
<h2>Batting</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th></th>
<th>
OverId
</th>
<th>
Ball
</th>
<th>
Runs
</th>
</tr>
@foreach (var Item in Model) {
<tr>
<td>
@* @Html.ActionLink("Edit", "Edit", new { id=item.DeliveryId }) |
@Html.ActionLink("Details", "Details", new { id=item.DeliveryId }) |
@Html.ActionLink("Delete", "Delete", new { id=item.DeliveryId })
*@ </td>
<td>
@Item.Key
</td>
<td>
@*item.Ball *@
</td>
<td>
@Item.Sum(x => x.Runs)
</td>
</tr>
}
</table>
答案 0 :(得分:1)
您可以创建类似
的ViewModelpublic class VMPlayerRuns
{
public Player _Player{get;set;}
public int Runs{get;set;}
}
你可以像
一样修改你的查询var batting = from d in deliveries
where d.Over.IsBatting == true
group d by d.Player into player
from p in player
select new VMPlayerRuns{Player = p.Key, p.Sum(x=>x.Runs)};
现在您可以将此viewmodel绑定到视图而不是复杂的笨拙分组。 * 注意: *查询中可能存在一些语法错误,但这是将分组投影到视图模型的全部想法