知识点思维导图

LINQ:C#语言集成查询详解
1. LINQ简介
语言集成查询(LINQ)是.NET框架的核心组件,允许在C#代码中直接使用类似SQL的语法操作数据集合。它通过统一的编程模型支持查询对象、数据库、XML等多种数据源,显著提升开发效率。
// 基础示例:整数集合筛选
var numbers = new List<int> { 5, 10, 15, 20 };
var result = from num in numbers
where num > 10
select num;
// 输出: [15, 20]
// 复杂示例:对象集合操作
class Product {
public string Name { get; set; }
public decimal Price { get; set; }
}
var products = new List<Product> {
new Product { Name = "Laptop", Price = 1200 },
new Product { Name = "Mouse", Price = 25 }
};
var expensiveItems = from p in products
where p.Price > 100
select p.Name;
// 输出: ["Laptop"]
2. LINQ优点
- 强类型检查:编译时类型安全
- 统一语法:跨数据源一致性操作
- 延迟执行:优化查询性能
- 可读性高:声明式语法接近自然语言
3. LINQ查询语法
使用from...where...select结构,类似SQL语法:
var query = from student in students
where student.Score > 90
orderby student.Name descending
select new { student.Name, student.Score };
4. LINQ查询方法
基于扩展方法的链式调用:
var result = students
.Where(s => s.Score > 90)
.OrderByDescending(s => s.Name)
.Select(s => new { s.Name, s.Score });
5. LINQ标准查询运算符
5.1 筛选运算符
Where:条件过滤
// 简单筛选
var adults = people.Where(p => p.Age >= 18);
// 多条件筛选
var vipCustomers = customers.Where(c =>
c.Level == "VIP" && c.PurchaseCount > 10);
5.2 投影运算符
Select:数据转换
// 提取属性
var names = products.Select(p => p.Name);
// 复杂转换
var summaries = orders.Select(o => new {
OrderID = o.ID,
Total = o.Items.Sum(item => item.Price * item.Quantity)
});
5.3 排序运算符
OrderBy/ThenBy:多级排序
// 单级排序
var sortedProducts = products.OrderBy(p => p.Price);
// 多级排序
var employees = employeeList
.OrderBy(e => e.Department)
.ThenByDescending(e => e.Salary);
5.4 分组运算符
GroupBy:数据分类
// 基础分组
var groupByDept = employees.GroupBy(e => e.Department);
// 分组统计
var salesData = orders
.GroupBy(o => o.SalesPerson)
.Select(g => new {
SalesPerson = g.Key,
TotalSales = g.Sum(o => o.Amount)
});
5.5 联接运算符
Join:数据源关联
var query = customers.Join(orders,
c => c.ID,
o => o.CustomerID,
(c, o) => new { c.Name, o.OrderDate });
5.6 聚合运算符
Sum/Average:数据汇总
// 简单聚合
var totalRevenue = orders.Sum(o => o.Amount);
// 条件聚合
var avgScore = students
.Where(s => s.Grade == "A")
.Average(s => s.Score);
5.7 转换运算符
5.7.1 AsEnumerable与AsQueryable
// AsEnumerable:强制后续操作在本地执行
var localQuery = dbContext.Products
.AsEnumerable()
.Where(p => p.Name.Contains("Pro"));
// AsQueryable:转换为可查询对象
IQueryable<Product> queryable = localList.AsQueryable();
5.7.2 Cast
类型安全转换:
IEnumerable objects = new object[] { 1, 2, 3 };
var integers = objects.Cast<int>(); // [1,2,3]
5.7.3 To运算符
ToArray:立即执行转数组
int[] array = query.ToArray();
ToList:立即执行转列表
List<Product> list = products.Where(p => p.Price > 100).ToList();
ToDictionary:键值对转换
// 简单转换
Dictionary<int, string> dict = products.ToDictionary(p => p.ID, p => p.Name);
// 复杂转换
var priceDict = products
.Where(p => p.Stock > 0)
.ToDictionary(
key => key.Category,
value => value.Price
);
结语
LINQ通过统一查询模型极大提升了C#的数据处理能力。掌握其运算符组合与延迟执行机制,能高效解决复杂数据场景问题。建议结合EF Core等框架实践数据库查询,深化理解。
4294

被折叠的 条评论
为什么被折叠?



