C# LINQ 表达式提供了一套统一的语法来查询各种数据源,包括集合、数据库和XML文档。以下是完整的语法指南:
LINQ 基础语法结构
?查询表达式语法?(类似SQL风格):
from 变量 in 数据源
where 条件
orderby 字段
select 结果
?方法语法?(使用 Lambda 表达式):
数据源.方法(参数 => 表达式)
核心查询子句详解
1. 数据源指定 - from 子句
每个LINQ查询必须以from子句开头,定义数据源和范围变量:
from item in collection
from num in numbers
from student in students
2. 条件筛选 - where 子句
基于布尔表达式筛选元素:
// 查询表达式
var result = from num in numbers
where num > 5 && num < 10
select num;
// 方法语法
var result = numbers.Where(num => num > 5 && num < 10);
3. 数据排序 - orderby 子句
// 升序排序
var result = from student in students
orderby student.Age
select student;
// 降序排序
var result = from student in students
orderby student.Age descending
select student;
// 多字段排序
var result = students.OrderBy(s => s.Age)
.ThenBy(s => s.Name);
4. 数据投影 - select 子句
// 选择特定字段
var names = from student in students
select student.Name;
// 创建匿名对象
var studentInfo = from student in students
select new { student.Name, student.Age };
5. 数据分组 - group 子句
var grouped = from student in students
group student by student.Occupation into g
select new { Occupation = g.Key, Count = g.Count() };
6. 连接查询 - join 子句
按照匹配条件联接两个数据源:
var joinResult = from student in students
join course in courses
on student.Id equals course.StudentId
select new { student.Name, course.CourseName };
常用LINQ操作方法
筛选操作
Where() - 条件筛选
OfType<T>() - 类型筛选
排序操作
OrderBy() - 升序排列
OrderByDescending() - 降序排列
ThenBy() / ThenByDescending() - 次级排序
投影操作
Select() - 数据转换
SelectMany() - 扁平化嵌套集合
分组操作
GroupBy() - 按键值分组
聚合操作
// 计数
int count = numbers.Count();
int conditionalCount = numbers.Count(n => n > 5);
// 求和
int sum = numbers.Sum();
// 极值
int max = numbers.Max();
int min = numbers.Min();
double average = numbers.Average();
元素操作
// 获取元素
var first = numbers.First();
var last = numbers.Last();
var single = numbers.Single(n => n == 5);
// 检查存在性
bool hasEven = numbers.Any(n => n % 2 == 0);
bool allPositive = numbers.All(n => n > 0);
分页操作
// 取前N个
var top3 = numbers.Take(3);
// 跳过前N个
var afterFirst3 = numbers.Skip(3);
// 组合分页
var page = numbers.Skip((pageNumber - 1) * pageSize)
.Take(pageSize);
高级LINQ特性
延迟执行
大多数LINQ查询采用延迟执行,只有在实际枚举结果时才会执行查询逻辑,这样可以构建复杂的查询链而不影响性能。
立即执行
某些操作会触发立即执行,如:Count(), ToList(), ToArray()
let 子句
创建临时变量用于复杂查询:
var result = from student in students
let fullName = student.FirstName + " " + student.LastName
where fullName.Length > 10
select fullName;
实际应用示例
?复杂查询组合?:
var complexQuery = from student in students
where student.Age > 18
orderby student.LastName, student.FirstName
group student by student.Department into deptGroup
select new {
Department = deptGroup.Key,
Count = deptGroup.Count(),
AverageAge = deptGroup.Average(s => s.Age)
};
查看更多关于C# 中LINQ表达式的语法大全的详细内容...