Problem description
You have a set of product data that needs to be packed according to the product code. For each code, you want to return an object that includes the product name, product quantity and total price. You are using Linq's groupby and selectmany functions to achieve this goal, but the quantitative attributes in the result objects are always 1.
Solution
The problem is that the SELECTMANY function is used to handle each item in each group. To solve this problem, use select instead.
alternative
<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>
Improved data type
Consider the change of the Quantity and Price attributes to int and decimal, respectively, because this can better reflect the nature of these values.
<code class="language-csharp">List<resultline> result = Lines .GroupBy(l => new { l.ProductCode, l.Name }) .Select(cl => new ResultLine { ProductName = cl.First().Name, Quantity = cl.Count().ToString(), Price = cl.Sum(c => c.Price).ToString(), }) .ToList();</code>
The above is the detailed content of How to Correctly Use LINQ's GroupBy, Sum, and Count to Aggregate Product Data?. For more information, please follow other related articles on the PHP Chinese website!