Home >Backend Development >C++ >Linq GroupBy: Why is my Count Always 1 Despite Multiple Occurrences?
Group, sum and count using LINQ
Question:
Given a collection of objects, group by a specific attribute, calculate the sum of another attribute, and count the number of occurrences of each group. The problem is that the count is always 1 even if there are multiple occurrences in the source collection.
Solution:
The reason for the wrong count calculation is the use of SelectMany in the code. This action causes every item in every group to be checked, thus skewing the count.
Please use the following code instead:
<code class="language-csharp">List<resultline> result = Lines .GroupBy(l => l.ProductCode) .Select(cl => new ResultLine { ProductName = cl.First().Name, Quantity = cl.Count().ToString(), Price = cl.Sum(c => c.Price).ToString(), }).ToList();</code>
This code uses First() to get the product name, assuming the product codes are consistent. It is recommended to define Quantity and Price as integer and decimal types respectively.
The above is the detailed content of Linq GroupBy: Why is my Count Always 1 Despite Multiple Occurrences?. For more information, please follow other related articles on the PHP Chinese website!