📅  最后修改于: 2023-12-03 14:43:54.457000             🧑  作者: Mango
LINQ(Language Integrated Query)是一种用于 .NET 平台的集成查询语言,它可以在.NET 编程语言(如 C# 和 VB.NET)中方便地执行数据查询。通过 LINQ 可以将查询与.NET 程序代码融为一体,从而实现对数据的强大操作。本备忘单提供一些常用的 LINQ 查询代码,以及对应的 SQL 语句。
var result = from p in Products
where p.Price > 100
select p;
SELECT * FROM Products WHERE Price > 100
var result = Products.Where(p => p.Price > 100);
SELECT * FROM Products WHERE Price > 100
var result = from p in Products
where p.Price > 100
select new { p.Name, p.Price };
SELECT Name, Price FROM Products WHERE Price > 100
var result = Products.Where(p => p.Price > 100)
.Select(p => new { p.Name, p.Price });
SELECT Name, Price FROM Products WHERE Price > 100
var result = from p in Products
orderby p.Price descending
select p;
SELECT * FROM Products ORDER BY Price DESC
var result = Products.OrderByDescending(p => p.Price);
SELECT * FROM Products ORDER BY Price DESC
var result = from p in Products
group p by p.Category into g
select new { Category = g.Key, Count = g.Count() };
SELECT Category, COUNT(*) AS Count FROM Products GROUP BY Category
var result = Products.GroupBy(p => p.Category)
.Select(g => new { Category = g.Key, Count = g.Count() });
SELECT Category, COUNT(*) AS Count FROM Products GROUP BY Category
var result = from p in Products
join s in Suppliers on p.SupplierID equals s.ID
select new { ProductName = p.Name, SupplierName = s.Name };
SELECT p.Name AS ProductName, s.Name AS SupplierName
FROM Products p JOIN Suppliers s ON p.SupplierID = s.ID
var result = Products.Join(Suppliers,
p => p.SupplierID,
s => s.ID,
(p, s) => new { ProductName = p.Name, SupplierName = s.Name });
SELECT p.Name AS ProductName, s.Name AS SupplierName
FROM Products p JOIN Suppliers s ON p.SupplierID = s.ID
var result = from c in Categories
select new { CategoryName = c.Name,
Products = from p in Products
where p.CategoryID == c.ID
select p };
SELECT c.Name AS CategoryName,
(SELECT * FROM Products WHERE CategoryID = c.ID) AS Products
FROM Categories c
var result = Categories.Select(c => new
{
CategoryName = c.Name,
Products = Products.Where(p => p.CategoryID == c.ID)
});
SELECT c.Name AS CategoryName,
(SELECT * FROM Products WHERE CategoryID = c.ID) AS Products
FROM Categories c
这些都是常见的 LINQ 查询技巧,可以提高编写 SQL 代码的效率。可以根据需要调整查询语法以实现更强大的操作。