Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aggregating within the foreach loop

Tags:

c#

asp.net-mvc

I have a loop:

<% foreach (User usedBy in discountDto.UsedBy)
   { %>
     <%=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
like image 989
justSteve Avatar asked Dec 08 '25 10:12

justSteve


1 Answers

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 />
<% } %>
like image 56
Marc Gravell Avatar answered Dec 09 '25 23:12

Marc Gravell