linq - 如何在 View 中使用 IGrouping 处理 IEnumerable?

标签 linq view ienumerable igrouping

我正在尝试向 View 发送 IEnumerable并显示其中的每个元素,但我发送它时遇到问题。它说:

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

我不知道如何处理它。

这是我的观点:
@model  IEnumerable<dynamic>

我得到 dynamic因为我从几个函数中看到了这个 View 如何发送不同的类型。
 <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>

我得到 IEnumerable从这个 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();

所以我的问题真的是:我怎样才能在 View 中获取它的元素?

最佳答案

您不能在 View 中引用该类型,因为它是匿名类型。相反,定义一个类型来存储查询结果:

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

然后将您的查询更改为该类型:
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();

然后你就可以绑定(bind)到类型 IEnumerable<Result>在你看来。

关于linq - 如何在 View 中使用 IGrouping 处理 IEnumerable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14293990/

相关文章:

iphone - iOS 7 中的 UIView 显示问题

c# - 如何在asp.net中的SQL表中存储IEnumerable<>数据值?

c# - 将 List<T> 中的数据绑定(bind)到 DatagridView

c# - LINQ to Entities 仅支持无参数构造函数和初始值设定项

android - 查询创建的 dbView(不是表)时出错!

c# - 在 Dynamic LINQ to Entities 中使用 DateTime

swift - 如何将对象限制为全屏

c# - 计算 IEnumerable<HttpPostedFileBase> 的非空元素

c# - 创建反向列表时出现 System.NotSupportedException

c# - orderby 无法使用 LINQ 获取子查询中的前 1 个结果