Home > Backend Development > C++ > How to Group Data by Multiple Columns Using LINQ?

How to Group Data by Multiple Columns Using LINQ?

Susan Sarandon
Release: 2025-01-31 15:36:14
Original
789 people have browsed it

How to Group Data by Multiple Columns Using LINQ?

LINQ uses linq according to multiple groups of group data

In SQL, you can use the group by clause based on multiple columns. This allows you to aggregate data based on the unique combination of the specified column.

LINQ provides a similar grouping mechanism with the Groupby extension method. However, unlike SQL, LINQ processes objects, which requires a way to identify the group standards.

To press multiple columns in Linq, you can use anonymous type to represent the group key. Anonymous type is a temporary and unnamed type that allows you to group the object based on a group of known attributes.

Consider the following SQL query:

To convert this query to linq, you can use anonymous type, as shown below:
<code class="language-sql">SELECT * FROM <table> GROUP BY <column1>, <column2></code>
Copy after login

This code is paid to the rows in the table based on the values ​​of Column1 and Column2. The generated groupdata variables are iGrouping & lt; TKEY, Telement & GT; where TKEY indicates the anonymous type for grouping, and Telement represents the rows in the group.
<code class="language-csharp">var groupedData = table.GroupBy(x => new { x.Column1, x.Column2 });</code>
Copy after login

Then you can iterate these groups and aggregate data as needed, which is similar to the method you do in SQL:

This code will be printed group key (anonymous types with column1 and column2 values) and each line in each group.
<code class="language-csharp">foreach (var group in groupedData)
{
    Console.WriteLine($"Group key: {group.Key}");
    Console.WriteLine("QuantityBreakdown:");

    foreach (var row in group)
    {
        Console.WriteLine($"  - MaterialID: {row.MaterialID}, ProductID: {row.ProductID}, Quantity: {row.Quantity}");
    }
}</code>
Copy after login

The above is the detailed content of How to Group Data by Multiple Columns Using LINQ?. 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