温馨提示×

如何用C# LINQ和Lambda操作集合

c#
小樊
83
2024-09-15 00:03:02
栏目: 编程语言

在C#中,LINQ(Language Integrated Query)和Lambda表达式提供了强大的方法来操作集合

  1. 使用LINQ查询集合:
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);
        }
    }
}
  1. 使用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 = numbers.Where(num => num % 2 == 0);

        Console.WriteLine("偶数:");
        foreach (var number in evenNumbers)
        {
            Console.WriteLine(number);
        }
    }
}
  1. 使用Lambda表达式对集合进行排序:
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);
        }
    }
}
  1. 使用Lambda表达式对集合进行转换:
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表达式操作集合。你可以根据需要修改这些示例以适应你的具体需求。

0