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

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

Linda Hamilton
Release: 2025-01-24 16:52:16
Original
333 people have browsed it

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

LINQ: GroupBy, Sum and Count

The goal of this code is to group a collection of products by product code and return an object containing the product name, the product quantity for each code, and the total price of each product.

The sample data contains three products:

<code>{"p1", 6.5, "Product1"}, {"p1", 6.5, "Product1"}, {"p2", 12, "Product2"}</code>
Copy after login

The expected results are as follows:

<code>Product1: count 2   - Price:13 (2x6.5)
Product2: count 1   - Price:12 (1x12)</code>
Copy after login
Copy after login

However, the count value generated by the code is incorrect, always showing 1 for each product.

The problem is that the SelectMany() method is used incorrectly. The code should use the Select() method, which simplifies expressions:

<code>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>
Copy after login

This modification corrects the problem and produces the desired count value:

<code>Product1: count 2   - Price:13 (2x6.5)
Product2: count 1   - Price:12 (1x12)</code>
Copy after login
Copy after login

The above is the detailed content of How to Correctly Use LINQ GroupBy, Sum, and Count to Aggregate Product Data?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template