views:

20

answers:

1

Hello All,

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>&nbsp;</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();


            var 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 :)

+1  A: 

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();
}
sTodorov
The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[System.Linq.IGrouping`2[System.String,MvcApplication1.Models.Log]]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[MvcApplication1.Models.Log]'.
Mage
The above is what I get
Mage
hey.... so in that case try the following:var s = (from logs in db.Logs group logs by logs.UserName into us select us).ToList();
sTodorov
Check edit above
sTodorov
doesnt work...same error
Mage