Linq query Group By error in ASP.NET MVC 2
I am having a bit of a struggle using linq and returning a list while trying to group.
In my view, I have the following:
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<IEnumerable<MvcApplication1.Models.Log>>" %>
<table>
<tr>
<th>
ID
</th>
<th>
User
</th>
<th>
NumberDialed
</th>
<th>
Date
</th>
<th>
Time
</th>
<th> </th>
</tr>
<% foreach (var item in Model)
{ %>
<tr>
<td>
<%: item.ID %>
</td>
<td>
<%: item.UserName %>
</td>
<td>
<%: item.NumberDialed %>
</td>
<td>
<%: item.Date %>
</td>
<td>
<%: item.Time %>
<%} %>
</td>
</table>
and in my controller I have:
public ActionResult Tenant()
{
LogEntities db = new LogEntities();
va开发者_开发问答r s = from logs in db.Logs
group logs by logs.UserName;
return View(s.ToList());
}
when I do a normal select it works:
public ActionResult Tenant()
{
using (LogEntities db = new LogEntities())
{
var s = from logs in db.Logs
orderby logs.UserName
select logs;
return View(s.ToList());
}
}
Why is using Group By not working and why it is so different? I want to be able to display the data by groups. How do I accomplish this?
Thanks :)
I think that in order to do a group you need to specify into what you need it to be grouped
var s = (from logs in db.Logs
group logs by logs.UserName into us
select us).ToList();
Then us.Key
gives you the username by which it is grouped and us
gives all the items that are grouped by this username.
Then you can do:
foreach(var userGroup in s){
var userName = us.Key;
var logs = us.ToList();
}
精彩评论