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

How to Group Data by Multiple Columns in LINQ?

DDD
DDDOriginal
2025-01-31 15:31:09285browse

How to Group Data by Multiple Columns in LINQ?

LINQ multiple groups of groups in detail

In SQL, you can use

clauses to group data based on multiple columns. For example:

GROUP BY

How to implement similar functions in Linq?
<code class="language-sql">SELECT * FROM <tablename> GROUP BY <column1>,<column2></code>

Use anonymous type

One method is to use anonymous type. The following is an example:

This code is grouped based on the

and
<code class="language-csharp">var groupedData = x.GroupBy(x => new { x.Column1, x.Column2 });</code>
attributes of the elements in the

sequence to create an anonymous type for each unique combination of value. x Column1 Data example Column2

Consider the following data structure:

and the following INSERT statement:

<code class="language-csharp">public class QuantityBreakdown
{
    public int MaterialID { get; set; }
    public int ProductID { get; set; }
    public float Quantity { get; set; }
}</code>
You can use the following code to convert this to linq:

<code class="language-sql">INSERT INTO @QuantityBreakdown (MaterialID, ProductID, Quantity)
SELECT MaterialID, ProductID, SUM(Quantity)
FROM @Transactions
GROUP BY MaterialID, ProductID</code>
This linq expression is paid according to

and

, and then calculates the sum of the
<code class="language-csharp">var groupedTransactions = transactions
    .GroupBy(t => new { t.MaterialID, t.ProductID })
    .Select(g => new QuantityBreakdown
    {
        MaterialID = g.Key.MaterialID,
        ProductID = g.Key.ProductID,
        Quantity = g.Sum(t => t.Quantity)
    });</code>
value of each group.

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