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

How to Group Data by Multiple Columns in LINQ?

DDD
Release: 2025-01-31 15:31:09
Original
220 people have browsed it

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

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

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template