在C#中,LINQ(Language Integrated Query)和Lambda表達(dá)式可以幫助你輕松地對(duì)數(shù)據(jù)進(jìn)行轉(zhuǎn)換
using System;
using System.Collections.Generic;
using System.Linq;
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
// 使用LINQ Select方法將數(shù)字列表轉(zhuǎn)換為字符串列表
var stringNumbers = numbers.Select(x => x.ToString());
// 使用LINQ Where方法篩選出偶數(shù)
var evenNumbers = numbers.Where(x => x % 2 == 0);
// 使用LINQ OrderBy方法對(duì)數(shù)字列表進(jìn)行排序
var sortedNumbers = numbers.OrderBy(x => x);
// 使用LINQ GroupBy方法根據(jù)奇偶性對(duì)數(shù)字列表進(jìn)行分組
var groupedNumbers = numbers.GroupBy(x => x % 2 == 0 ? "Even" : "Odd");
Console.WriteLine("String Numbers:");
foreach (var num in stringNumbers)
{
Console.WriteLine(num);
}
Console.WriteLine("\nEven Numbers:");
foreach (var num in evenNumbers)
{
Console.WriteLine(num);
}
Console.WriteLine("\nSorted Numbers:");
foreach (var num in sortedNumbers)
{
Console.WriteLine(num);
}
Console.WriteLine("\nGrouped Numbers:");
foreach (var group in groupedNumbers)
{
Console.WriteLine($"Group: {group.Key}");
foreach (var num in group)
{
Console.WriteLine(num);
}
}
這個(gè)示例展示了如何使用LINQ和Lambda表達(dá)式對(duì)數(shù)據(jù)進(jìn)行轉(zhuǎn)換。你可以根據(jù)需要調(diào)整查詢條件和轉(zhuǎn)換操作。