在C#中,LINQ(Language Integrated Query)和Lambda表達式提供了強大的方法來操作集合
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 };
var evenNumbers = from num in numbers
where num % 2 == 0
select num;
Console.WriteLine("偶數:");
foreach (var number in evenNumbers)
{
Console.WriteLine(number);
}
}
}
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 };
var evenNumbers = numbers.Where(num => num % 2 == 0);
Console.WriteLine("偶數:");
foreach (var number in evenNumbers)
{
Console.WriteLine(number);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
List<int> numbers = new List<int> { 5, 3, 1, 4, 2 };
var sortedNumbers = numbers.OrderBy(num => num);
Console.WriteLine("排序后的數字:");
foreach (var number in sortedNumbers)
{
Console.WriteLine(number);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
List<string> words = new List<string> { "apple", "banana", "cherry" };
var uppercaseWords = words.Select(word => word.ToUpper());
Console.WriteLine("轉換為大寫:");
foreach (var word in uppercaseWords)
{
Console.WriteLine(word);
}
}
}
這些示例展示了如何使用LINQ和Lambda表達式操作集合。你可以根據需要修改這些示例以適應你的具體需求。