如何在ASP.NET MVC视图中对数据进行分组?

时间:2021-03-22 04:06:17

In reporting tools like Crystal Reports, there are ways to take denormalized data and group it by a particular column in the data, creating row headings for each unique item in the specified column.

在Crystal Reports等报表工具中,有一些方法可以获取非规范化数据并将其按数据中的特定列分组,从而为指定列中的每个唯一项创建行标题。

If I have this:

如果我有这个:

Category1    Data1
Category1    Data2
Category1    Data3
Category2    Data4
Category2    Data5
Category2    Data6

The reporting software will group it like this:

报告软件会将其分组如下:

Category1
      Data1
      Data2
      Date3
Category2
      Data4
      Data5
      Data6

Is there a way to do this in an ASP.NET MVC view, perhaps using a simple linq phrase or linq extension method with a foreach or a nested foreach?

有没有办法在ASP.NET MVC视图中执行此操作,可能使用简单的linq短语或linq扩展方法与foreach或嵌套的foreach?

1 个解决方案

#1


43  

If your view is strongly typed, you can use the LINQ GroupBy extension method with nested foreach:

如果您的视图是强类型的,则可以将LINQ GroupBy扩展方法与嵌套的foreach一起使用:

<ul>
<% foreach (var group in Model.GroupBy(item => item.Category)) { %>

   <li><%= Html.Encode(group.Key) %>
     <ul>

     <% foreach (var item in group) { %>
       <li><%= Html.Encode(item.Data) %></li>  
     <% } %>

     </ul>
   </li>

<% } %>
</ul>

This will provide output much like your formatted lists in the original question. It assumes your model looks something like:

这将提供与原始问题中的格式化列表非常相似的输出。它假设您的模型看起来像:

public class ViewModel
{
    public string Category { get; set; }
    public string Data { get; set; }
}

#1


43  

If your view is strongly typed, you can use the LINQ GroupBy extension method with nested foreach:

如果您的视图是强类型的,则可以将LINQ GroupBy扩展方法与嵌套的foreach一起使用:

<ul>
<% foreach (var group in Model.GroupBy(item => item.Category)) { %>

   <li><%= Html.Encode(group.Key) %>
     <ul>

     <% foreach (var item in group) { %>
       <li><%= Html.Encode(item.Data) %></li>  
     <% } %>

     </ul>
   </li>

<% } %>
</ul>

This will provide output much like your formatted lists in the original question. It assumes your model looks something like:

这将提供与原始问题中的格式化列表非常相似的输出。它假设您的模型看起来像:

public class ViewModel
{
    public string Category { get; set; }
    public string Data { get; set; }
}