[英]Displaying item other than key with groupby foreach loop c# asp.net mvc
I am currently using groupby with a foreach loop to show a list of nested records. 我目前正在使用带有foreach循环的groupby来显示嵌套记录的列表。
However I want to us an id as the key, so that I can use it to make dynamic css selectors etc.. 但是我想给我们一个id作为键,以便我可以用它来创建动态的CSS选择器等。
But I want to be able to show the name of each of the groups before the secondarly loop is iterated through. 但我希望能够在遍历第二循环之前显示每个组的名称。
I think the code will make it more clear. 我认为代码将使其更加清晰。
Basically it would be great if I could access properties other than group.key before the second loop starts. 基本上,如果在第二个循环开始之前我可以访问group.key以外的属性,那就太好了。
I know I could limit the iterations of the title loop, but it feels very wrong 我知道我可以限制标题循环的迭代,但是感觉很错误
<ul id="GoalAndTaskList">
<% foreach (var group in Model.GroupBy(item => item.goalId)) { %>
<li>
/////This code is just to display the name, but it iterates
/////through the whole group, so the title is rendered many times
<% foreach (var item in group)
{ %>
<%= Html.Encode(item.goalName) %>
<% } %>
///////// Before this I was using group.key , which meant an Id was the title
/////////
<table id="taskTable<%= Html.Encode(group.Key) %>">
<% foreach (var item in group) { %>
<tr id="<%= Html.Encode(item.sortOrder) %>">
<td class="dragHandle"> </td>
<td><%= Html.Encode(item.sortOrder) %></td>
<td>
<input type="text" name="<%= Html.Encode(item.taskId) %>" value="<%=Html.Encode(item.taskName) %>"/>
</td>
<td>
<a id="DeleteTask<%= Html.Encode(item.taskId) %>">Delete Task</a>
</td>
</tr>
<% } %>
</table>
<br /><a id="AddNew2<%= Html.Encode(group.Key) %>">Add new task</a><br /><br />
</li>
<% } %>
</ul>
What I did was this 我所做的就是这个
<% foreach (var item in group.Take(1))
{ %>
<%= Html.Encode(item.goalName) %>
<% } %>
It feels really wrong though to do it like this, can anyone suggest a cleaner way of doing this? 这样做确实感觉很错误,有人可以建议一种更清洁的方式吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.