在C#中,LINQ(Language Integrated Query)和Lambda表达式提供了强大的方法来操作集合
- 使用LINQ查询集合:
using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { Listnumbers = new List { 1, 2, 3, 4, 5 }; var evenNumbers = from num in numbers where num % 2 == 0 select num; Console.WriteLine("偶数:"); foreach (var number in evenNumbers) { Console.WriteLine(number); } } }
- 使用Lambda表达式过滤集合:
using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { Listnumbers = new List { 1, 2, 3, 4, 5 }; var evenNumbers = numbers.Where(num => num % 2 == 0); Console.WriteLine("偶数:"); foreach (var number in evenNumbers) { Console.WriteLine(number); } } }
- 使用Lambda表达式对集合进行排序:
using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { Listnumbers = new List { 5, 3, 1, 4, 2 }; var sortedNumbers = numbers.OrderBy(num => num); Console.WriteLine("排序后的数字:"); foreach (var number in sortedNumbers) { Console.WriteLine(number); } } }
- 使用Lambda表达式对集合进行转换:
using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { Listwords = new List { "apple", "banana", "cherry" }; var uppercaseWords = words.Select(word => word.ToUpper()); Console.WriteLine("转换为大写:"); foreach (var word in uppercaseWords) { Console.WriteLine(word); } } }
这些示例展示了如何使用LINQ和Lambda表达式操作集合。你可以根据需要修改这些示例以适应你的具体需求。