Home >Backend Development >C++ >How to Correctly Use LINQ's GroupBy, Sum, and Count to Aggregate Product Data?

How to Correctly Use LINQ's GroupBy, Sum, and Count to Aggregate Product Data?

Linda Hamilton
Linda HamiltonOriginal
2025-01-24 16:56:13293browse

How to Correctly Use LINQ's GroupBy, Sum, and Count to Aggregate Product Data?

linq: Groupby, Sum, and Count

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>
Or, you can group the product name and product code at the same time. If the name of the given code is always the same, the same results will be obtained. This can be generated in EF to generate better SQL:

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn