Home >Backend Development >C++ >How to Group Data by Multiple Columns in LINQ?
In SQL, you can use
clauses to group data based on multiple columns. For example:
GROUP BY
<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!