我有一个循环:
<% foreach (User usedBy in discountDto.UsedBy)
{ %>
<%=usedBy.FullName%><br />
<% } %>
通常会生成多个具有相同名称的行:
Bob Smith
Mark Thomas
Mark Thomas
Steve Jones
我想将多行聚合到一行,后跟一个表示该名称出现次数的整数:
Bob Smith
Mark Thomas (2)
Steve Jones
答案 0 :(得分:9)
请原谅格式化 - 错误的工具“交出”......
foreach (User usedBy in discountDto.UsedBy.GroupBy(x => x.FullName))
{
var count = usedBy.Count();
%><%=usedBy.Key%><%
if(count>1) %><%=" (" + count + ")"%><%
%><br />
<% } %>
答案 1 :(得分:1)
var aggregatedUsers=from users in discountDto.UsedBy
group user by user.FullName into result
select new
{
User=result.Key,
Count= result.Count(),
};
答案 2 :(得分:1)
这样的事对我有用
foreach (var item in list.GroupBy(u => new {u.Surname, u.FirstName}))
{
%>
<%=Html.Encode(item.Key.FirstName)%>
<%=Html.Encode(item.Key.Surname)%>
<%
if (item.Count) > 1)
{
%>
(<%=item.Count%>)
<%
}
}
答案 3 :(得分:0)
试试这个:请原谅我的语法不好......我的Asp.Net生锈了,希望你明白这个想法......
<%
Dictionary<string,int> counts = new Dictionary<string, int>();
foreach (User usedBy in discountDto.UsedBy)
{ %>
<%if (counts.Contains(usedBy.FullName)) counts[usedBy.FullName]++;
else counts.Add(usedBy.FullName, 1);
} %>
<% foreach(string usdBy in counts)
{ %>
<%=usdBy%><br /><%
<%if (counts[usdBy] > 1)
{%>
(<%=counts[usdBy];%>) <%
}%>
} %>