在 C# 中,LINQ(Language Integrated Query)是一种强大的查询技术,它允许你使用熟悉的 C# 语法来查询数据集合。LINQ 可以用于查询各种数据源,包括数组、列表、数据集、SQL数据库等。
以下是一些基本的 LINQ 语句示例:
-
简单查询:
var query = from item in collection select item;
-
筛选:
var query = from item in collection where item.SomeProperty > 10 select item;
-
排序:
var query = from item in collection orderby item.SomeProperty ascending select item;
-
筛选和排序:
var query = from item in collection where item.SomeProperty > 10 orderby item.AnotherProperty descending select item;
-
选择特定列:
var query = from item in collection select new { item.SomeProperty, item.AnotherProperty };
-
分组:
var query = from item in collection group item by item.SomeProperty into g select new { Key = g.Key, Items = g };
-
联接:
var query = from item1 in collection1 join item2 in collection2 on item1.ID equals item2.ID select new { item1, item2 };
-
聚合:
int count = collection.Count(); int sum = collection.Sum(item => item.SomeProperty); double average = collection.Average(item => item.SomeProperty);
-
元素操作:
T first = collection.FirstOrDefault(); T single = collection.SingleOrDefault(item => item.SomeProperty == value); bool any = collection.Any(item => item.SomeProperty > 10);
-
转换:
var query = collection.Select(item => item.Transform());
-
去重:
var distinctItems = collection.Distinct();
-
分页:
var pagedItems = collection.Skip(pageNumber * pageSize).Take(pageSize);
-
复合查询:
var query = from item in collection where item.SomeProperty > 10 orderby item.AnotherProperty descending select new { item.SomeProperty, item.AnotherProperty } into projected where projected.SomeProperty > 20 select projected;
-
使用匿名类型:
var query = from item in collection select new { item.SomeProperty, item.AnotherProperty };
-
使用扩展方法:
var results = collection.Where(item => item.SomeProperty > 10).ToList();
使用 LINQ 进行数据的分组和聚合操作
在 C# 中使用 LINQ 进行数据的分组和聚合操作是一种常见的任务,它允许你将数据集合中的元素按照某个或某些键进行分组,并在每个分组上执行聚合操作,如求和、平均、最大、最小等。以下是如何使用 LINQ 进行分组和聚合的一些示例:
分组操作
假设你有一个 Product
类和一个包含多个 Product
实例的列表,你想按照产品类别对产品进行分组:
public class Product
{
public string Category { get; set; }
public decimal Price { get; set; }
// 其他属性...
}
List<Product> products = // 假设这是你的产品列表
var groupedProducts = products.GroupBy(p => p.Category);
groupedProducts
现在是一个包含分组的集合,每个分组的键是类别,值是具有相同类别的产品列表。
聚合操作
在分组的基础上,你可以进行聚合操作。例如,计算每个类别的产品总价:
var totalSalesByCategory = products.GroupBy(p => p.Category)
.Select(g => new { Category = g.Key, TotalSales = g.Sum(p => p.Price) });
在这个例子中,Sum
是聚合函数,它对每个分组中的 Price
属性进行求和。
组合分组和聚合
你可以组合多个聚合操作,例如,计算每个类别的产品数量、平均价格和最贵产品:
var aggregatedResults = products.GroupBy(p => p.Category)
.Select(g => new
{
Category = g.Key,
Count = g.Count(),
AveragePrice = g.Average(p => p.Price),
MostExpensiveProduct = g.Max(p => p.Price)
});
使用匿名类型
在 LINQ 查询中,你可以使用匿名类型来存储聚合结果,这在不创建具体类的情况下非常有用:
var query = products.GroupBy(p => p.Category)
.Select(g => new
{
Category = g.Key,
TotalItems = g.Count(),
AveragePrice = g.Average(p => p.Price)
});
分组和连接
如果你需要在分组后对每个分组进行更复杂的操作,比如连接另一个集合,你可以这样做:
var categories = new[] { "Beverages", "Food", "Electronics" }; // 假设这是你的类别列表
var groupedWithDetails = categories.GroupJoin(products,
category => category,
product => product.Category,
(category, products) => new
{
Category = category,
Products = products.DefaultIfEmpty(),
HasProducts = products.Any()
});
在这个例子中,GroupJoin
用于将类别列表与产品列表连接,即使某些类别没有产品也会包含在结果中。
注意事项
- 聚合方法如
Sum
、Average
、Max
、Min
等,要求指定的属性是数值类型。 - 分组和聚合操作通常在数据集合上执行,如
List<T>
、IEnumerable<T>
等。 - 分组和聚合操作是延时执行的,即只有在你枚举结果时才会执行查询。