Search code examples
linqviewienumerableigrouping

How to handle IEnumerable with IGrouping in the view?


I am trying to send to the view an IEnumerable and to show every element in it but I have a problem when I send it. It says that:

{System.Linq.Enumerable.WhereSelectEnumerableIterator<System.Linq.IGrouping<string,MvcApplication4.Models.USER>,<>f__AnonymousType8<string,int>>}

and I dont know how to handle it.

This is my view :

@model  IEnumerable<dynamic>

I get dynamic because i go to this view from couple of functions how send different types.

 <table border="1"  style="text-align:center">
      <tr>
          <td> </td>
          <td> user name </td>  
          <td>age </td>  
          <td>comments </td>
      </tr>

      @foreach (var t in (Model))
      {
      <tr>                                           
          <td>@(count++))</td>
          <td> @Console.WriteLine(t)</td>  
          <td>  </td>  
          <td> </td>
      </tr>                                    
      }

 </table>

I get the IEnumerable from this linq :

 var allU = (from m in comList
                    join c in users on m.user equals c.user into cm1
                    from cm2 in cm1.DefaultIfEmpty()
                    group cm2 by m.user into grouped
                    select new { name = grouped.Key, count = grouped.Count() }).AsEnumerable();

So my question is really : how can I get the elements of it in the view?


Solution

  • You can't reference the type in your view because it is an anonymous type. Instead, define a type to store the results of your query:

    public class Result
    {
      public string Name { get; set; }
      public int Count { get; set; }
    }
    

    Then change your query to project into that type:

    var allU = (from m in comList
                        join c in users on m.user equals c.user into cm1
                        from cm2 in cm1.DefaultIfEmpty()
                        group cm2 by m.user into grouped
                        select new Result { Name = grouped.Key, Count = grouped.Count() }).AsEnumerable();
    

    Then you'll be able to bind to the type IEnumerable<Result> in your view.