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>
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>
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>
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!