List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; // 筛选 var evenNumbers = numbers.Where(n => n % 2 == 0).ToList(); Console.WriteLine("偶数:"); foreach (var number in evenNumbers) { Console.WriteLine(number); } // 转换 var squared = numbers.Select(n => n * n).ToList(); Console.WriteLine("平方:"); foreach (var number in squared) { Console.WriteLine(number); } // 聚合 var sum = numbers.Sum(); var average = numbers.Average(); var max = numbers.Max(); Console.WriteLine($"总和:{sum}"); Console.WriteLine($"平均值:{average}"); Console.WriteLine($"最大值:{max}");
实际应用示例
学生成绩管理
namespace AppList { publicclassStudent { publicstring Name { get; set; } publicint Score { get; set; } } internal classProgram { staticvoidMain(string[] args) { // 创建学生列表 List<Student> students = new List<Student> { new Student { Name = "Alice", Score = 95 }, new Student { Name = "Bob", Score = 85 }, new Student { Name = "Charlie", Score = 90 } }; // 查找成绩最高的学生 var topStudent = students.OrderByDescending(s => s.Score).First(); // 计算平均分 var averageScore = students.Average(s => s.Score); // 找出及格的学生 var passedStudents = students.FindAll(s => s.Score >= 60); Console.WriteLine($"最高分学生:{topStudent.Name},成绩:{topStudent.Score}"); Console.WriteLine($"平均分:{averageScore}"); Console.WriteLine("及格学生:"); foreach (var student in passedStudents) { Console.WriteLine($"{student.Name},成绩:{student.Score}"); } } } }