📜  LINQ: 2 join with group by - C# (1)

📅  最后修改于: 2023-12-03 15:02:41.674000             🧑  作者: Mango

LINQ: Two Joins with Group By - C#

In this tutorial, we will explore how to use LINQ to perform two joins with a group by command in C#.

Introduction

LINQ is an acronym for Language-Integrated Query, which is a component that allows developers to query data from different data sources using the same syntax. The flexibility of LINQ allows developers to use LINQ with databases, XML documents, and in-memory objects.

In this tutorial, we will query data from two different tables with a group by command. We will write a LINQ query to get sales data from two tables, Sales and Customers. The Sales table contains the sales transaction details, while the Customers table contains information about the customers who made the purchase.

The Data

For the purpose of this tutorial, assume that the two tables, Sales and Customers, in the database have the following fields:

Sales Table
  • SalesID (int)
  • CustomerID (int)
  • DateSold (datetime)
  • ItemSold (varchar)
  • QuantitySold (int)
Customers Table
  • CustomerID (int)
  • FirstName (varchar)
  • LastName (varchar)
  • Email (varchar)
  • Address (varchar)
The Query

To get the sales data from both tables, we need to write a query that joins the two tables on the CustomerID field and groups the results by the customer's full name.

var salesByCustomer = (from s in Sales
                       join c in Customers on s.CustomerID equals c.CustomerID
                       group s by new { c.FirstName, c.LastName } into g
                       select new
                       {
                           FullName = g.Key.FirstName + " " + g.Key.LastName,
                           TotalSales = g.Sum(x => x.QuantitySold),
                           AverageSale = g.Average(x => x.QuantitySold),
                           LargestSale = g.Max(x => x.QuantitySold),
                           SmallestSale = g.Min(x => x.QuantitySold)
                       }).ToList();

This LINQ query joins the Sales table and the Customers table on the CustomerID field using the join clause. The group by clause is used to group the results by the customer's full name created by c.FirstName and c.LastName as a new anonymous object.

We then select a projection that creates a new object with the FullName, TotalSales, AverageSale, LargestSale, and SmallestSale fields. These fields are calculated with the Sum, Average, Max, and Min methods respectively.

Finally, the ToList() extension method is called to execute the query and return the results as a list.

Conclusion

In this tutorial, we have learned how to use LINQ to perform two joins with a group by command in C#. LINQ is a powerful tool that allows developers to query data from different data sources using the same syntax. By applying knowledge of LINQ, developers can write more efficient and readable code.