我一直在为在MVC视图中使用C#将数据矩阵/数据转换为HTML表格而烦恼。
似乎我可以通过分组开始,然后在组内分组以生成标签和数据:
<table class="table table-striped table-bordered">
<thead class="thead-inverse">
<tr >
<th></th>
@foreach (var responsiblityGroup in @Model.PAssets.GroupBy(x => x.Responsibility))
{
<th>@responsiblityGroup.Key</th>
}
</tr>
</thead>
<tbody>
@foreach (var typeGroup in @Model.PAssets.GroupBy(x => x.Type))
{
<tr>
<td>@typeGroup.Key</td>
@foreach (var responsibiltyGroup in typeGroup.GroupBy(x => x.Responsibility))
{
<td>@responsibiltyGroup.Count()</td>
}
</tr>
}
</tbody>
</table>
但很明显,我没有为没有项目的群体设置一个单元格,并且数据错误地位于第一列可用,即
。
我想知道,有没有办法强制显示这些组的计数为0?
修改
以下评论我首先尝试在表格中构建数据:
static void Main(string[] args)
{
var myList = new List<ListItem>();
myList.Add(new ListItem("IT", "Cat"));
myList.Add(new ListItem("IT", "Cat"));
myList.Add(new ListItem("IT", "Owl"));
myList.Add(new ListItem("DE", "Dog"));
myList.Add(new ListItem("BU", "Cat"));
myList.Add(new ListItem("BU", "Dog"));
myList.Add(new ListItem("BU", "Dog"));
myList.Add(new ListItem("PR", "Dog"));
myList.Add(new ListItem("PR", "Owl"));
var roleGroup = myList.GroupBy(x => x.Role).OrderBy(y => y.Key);
var roleGroupNo = myList.GroupBy(x => x.Role).Count();
var typeGroup = myList.OrderBy(x => x.Type).GroupBy(x => x.Type);
var typeGroupNo = myList.GroupBy(x => x.Type).Count();
var roleGroupHeader = new string[roleGroupNo];
var roleIndex = -1;
foreach (var header in roleGroup)
{
roleIndex++;
roleGroupHeader[roleIndex] = header.Key;
}
var typeGroupHeader = new string[typeGroupNo];
var typeIndex = -1;
foreach (var header in typeGroup)
{
typeIndex++;
typeGroupHeader[typeIndex] = header.Key;
}
var dataGrid = new int[roleGroupNo, typeGroupNo];
foreach (var item in myList)
{
int x = Array.IndexOf(roleGroupHeader, item.Role);
int y = Array.IndexOf(typeGroupHeader, item.Type);
dataGrid[x, y]++;
}
Console.Write($" ");
for (int i = 0; i < typeGroupNo; i++)
{
Console.Write($"{typeGroupHeader[i]},");
}
Console.WriteLine();
for (int i = 0; i < roleGroupNo; i++)
{
Console.Write($"{roleGroupHeader[i]}, ");
for (int j = 0; j < typeGroupNo; j++)
{
Console.Write($"{dataGrid[i, j]},");
}
Console.WriteLine();
}
Console.ReadLine();
}
}
public class ListItem
{
public string Role { get; set; }
public string Type { get; set; }
public ListItem(string role, string type)
{
this.Role = role;
this.Type = type;
}
}