在.NET框架中,LINQ提供了一系列操作符来简化数据查询和处理逻辑,总共可以分为9类,分别是筛选操作符、投影操作符、排序操作符、连接操作符、分组操作符、聚合操作符、集合操作符、元素操作符、量词操作符。这些操作符覆盖了日常开发中绝大多数的数据操作需求,下面分别介绍每类操作符的使用方法并给出对应示例代码。

1. 筛选操作符
筛选操作符用于从数据源中筛选出符合条件的元素,常用的有Where和OfType。
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
// Where筛选大于5的元素
var filteredNumbers = numbers.Where(n => n > 5).ToList();
Console.WriteLine("筛选出的大于5的数字:");
filteredNumbers.ForEach(n => Console.Write(n + " "));
List<object> mixedList = new List<object> { 1, "hello", 2, "world", 3 };
// OfType筛选指定类型的元素
var intList = mixedList.OfType<int>().ToList();
Console.WriteLine("\n筛选出的整数元素:");
intList.ForEach(n => Console.Write(n + " "));
}
}2. 投影操作符
投影操作符用于将元素转换为新的形式,常用的是Select和SelectMany。
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
List<string> names = new List<string> { "张三", "李四", "王五" };
// Select将每个元素转换为带前缀的新字符串
var prefixedNames = names.Select(name => "用户:" + name).ToList();
Console.WriteLine("投影后的名称:");
prefixedNames.ForEach(n => Console.WriteLine(n));
List<List<int>> numberGroups = new List<List<int>>
{
new List<int> { 1, 2 },
new List<int> { 3, 4 }
};
// SelectMany将嵌套集合展开为扁平集合
var flattenedNumbers = numberGroups.SelectMany(group => group).ToList();
Console.WriteLine("展开后的数字:");
flattenedNumbers.ForEach(n => Console.Write(n + " "));
}
}3. 排序操作符
排序操作符用于对元素进行排序,常用的有OrderBy、OrderByDescending、ThenBy。
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
List<int> numbers = new List<int> { 5, 2, 8, 1, 9 };
// 升序排序
var ascNumbers = numbers.OrderBy(n => n).ToList();
Console.WriteLine("升序排序结果:");
ascNumbers.ForEach(n => Console.Write(n + " "));
// 降序排序
var descNumbers = numbers.OrderByDescending(n => n).ToList();
Console.WriteLine("\n降序排序结果:");
descNumbers.ForEach(n => Console.Write(n + " "));
List<Student> students = new List<Student>
{
new Student { Name = "张三", Score = 80 },
new Student { Name = "李四", Score = 90 },
new Student { Name = "王五", Score = 80 }
};
// 先按分数降序,分数相同再按名称升序
var sortedStudents = students.OrderByDescending(s => s.Score).ThenBy(s => s.Name).ToList();
Console.WriteLine("\n学生排序结果:");
sortedStudents.ForEach(s => Console.WriteLine($"{s.Name}:{s.Score}"));
}
}
class Student
{
public string Name { get; set; }
public int Score { get; set; }
}4. 连接操作符
连接操作符用于将两个数据源按照关联条件进行连接,常用的是Join。
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
List<Student> students = new List<Student>
{
new Student { Id = 1, Name = "张三" },
new Student { Id = 2, Name = "李四" }
};
List<Score> scores = new List<Score>
{
new Score { StudentId = 1, Subject = "数学", Value = 90 },
new Score { StudentId = 1, Subject = "语文", Value = 85 },
new Score { StudentId = 2, Subject = "数学", Value = 88 }
};
// 内连接学生和成绩数据
var studentScores = students.Join(scores,
s => s.Id,
sc => sc.StudentId,
(s, sc) => new { s.Name, sc.Subject, sc.Value }
).ToList();
Console.WriteLine("学生成绩连接结果:");
studentScores.ForEach(item => Console.WriteLine($"{item.Name}的{item.Subject}成绩:{item.Value}"));
}
}
class Student
{
public int Id { get; set; }
public string Name { get; set; }
}
class Score
{
public int StudentId { get; set; }
public string Subject { get; set; }
public int Value { get; set; }
}5. 分组操作符
分组操作符用于按照指定条件对元素进行分组,常用的是GroupBy。
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
List<string> words = new List<string> { "apple", "banana", "apricot", "blueberry", "cherry" };
// 按首字母分组
var groupedWords = words.GroupBy(w => w[0]).ToList();
Console.WriteLine("按首字母分组结果:");
foreach (var group in groupedWords)
{
Console.WriteLine($"首字母{group.Key}的单词:");
foreach (var word in group)
{
Console.Write(word + " ");
}
Console.WriteLine();
}
}
}6. 聚合操作符
聚合操作符用于对元素进行统计计算,常用的有Count、Sum、Average、Max、Min。
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
Console.WriteLine($"元素数量:{numbers.Count()}");
Console.WriteLine($"元素总和:{numbers.Sum()}");
Console.WriteLine($"元素平均值:{numbers.Average()}");
Console.WriteLine($"元素最大值:{numbers.Max()}");
Console.WriteLine($"元素最小值:{numbers.Min()}");
}
}7. 集合操作符
集合操作符用于对两个集合进行交并补等操作,常用的有Union、Intersect、Except。
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
List<int> set1 = new List<int> { 1, 2, 3, 4 };
List<int> set2 = new List<int> { 3, 4, 5, 6 };
// 并集
var unionSet = set1.Union(set2).ToList();
Console.WriteLine("并集结果:");
unionSet.ForEach(n => Console.Write(n + " "));
// 交集
var intersectSet = set1.Intersect(set2).ToList();
Console.WriteLine("\n交集结果:");
intersectSet.ForEach(n => Console.Write(n + " "));
// 差集(set1中有的set2没有的)
var exceptSet = set1.Except(set2).ToList();
Console.WriteLine("\n差集结果:");
exceptSet.ForEach(n => Console.Write(n + " "));
}
}8. 元素操作符
元素操作符用于获取集合中的单个元素,常用的有First、FirstOrDefault、Single、ElementAt。
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
// 获取第一个元素
Console.WriteLine($"第一个元素:{numbers.First()}");
// 获取第一个大于3的元素
Console.WriteLine($"第一个大于3的元素:{numbers.First(n => n > 3)}");
// 获取指定索引的元素
Console.WriteLine($"索引2的元素:{numbers.ElementAt(2)}");
// 获取第一个大于10的元素,没有则返回默认值
Console.WriteLine($"第一个大于10的元素(不存在):{numbers.FirstOrDefault(n => n > 10)}");
}
}9. 量词操作符
量词操作符用于判断集合中元素是否满足特定条件,常用的有Any、All、Contains。
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
// 是否存在大于3的元素
Console.WriteLine($"是否存在大于3的元素:{numbers.Any(n => n > 3)}");
// 是否所有元素都大于0
Console.WriteLine($"是否所有元素都大于0:{numbers.All(n => n > 0)}");
// 是否包含元素3
Console.WriteLine($"是否包含元素3:{numbers.Contains(3)}");
}
}