Aggregation inside the foreach loop

I have a loop:

<% foreach (User usedBy in discountDto.UsedBy)
   { %>
     <%=usedBy.FullName%><br />
<% } %>

which often creates multiple lines with the same name:

Bob Smith
Mark Thomas
Mark Thomas
Steve Jones

I would like to combine several lines into one line, followed by an integer representing the number of times this happened:

Bob Smith
Mark Thomas (2)
Steve Jones
+3
source share
4 answers

I apologize for the formatting - the wrong tools to "hand in" ...

foreach (User usedBy in discountDto.UsedBy.GroupBy(x => x.FullName))
{
    var count = usedBy.Count();
  %><%=usedBy.Key%><%
       if(count>1) %><%=" (" + count + ")"%><%
     %><br />
<% } %>
+9
source
var aggregatedUsers=from users in discountDto.UsedBy
                                    group user by user.FullName into result
                                    select new 
                                        {
                                            User=result.Key,
                                            Count= result.Count(),
                                        };
+1
source

-

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%>)
        <%
    }
}
+1

: , ... 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];%>) <%
        }%>
   } %>
0

Source: https://habr.com/ru/post/1724307/


All Articles