Aggregating within the foreach loop
I have a loop:
<% foreach (User usedBy in discountDto.开发者_如何学JAVAUsedBy)
{ %>
<%=usedBy.FullName%><br />
<% } %>
that often produces multiple lines with the same name:
Bob Smith
Mark Thomas
Mark Thomas
Steve Jones
I would like to aggregate the multiple lines to a single line followed by an integer representing the number of times that name occurred:
Bob Smith
Mark Thomas (2)
Steve Jones
Please excuse formatting - wrong tools "to hand"...
foreach (User usedBy in discountDto.UsedBy.GroupBy(x => x.FullName))
{
var count = usedBy.Count();
%><%=usedBy.Key%><%
if(count>1) %><%=" (" + count + ")"%><%
%><br />
<% } %>
var aggregatedUsers=from users in discountDto.UsedBy
group user by user.FullName into result
select new
{
User=result.Key,
Count= result.Count(),
};
Something like this worked for me
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%>)
<%
}
}
Try this: Please excuse the poor syntax... my Asp.Net is rusty, hope you get the idea...
<%
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];%>) <%
}%>
} %>
精彩评论