首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何从C#中的LinkedList中删除与给定条件匹配的元素?

要从C#中的LinkedList中删除与给定条件匹配的元素,您可以使用以下步骤:

  1. 首先,确保已经引用了System.Collections.Generic和System.Linq命名空间。
代码语言:csharp
复制
using System.Collections.Generic;
using System.Linq;
  1. 创建一个LinkedList并添加一些元素。
代码语言:csharp
复制
LinkedList<int> linkedList = new LinkedList<int>();
linkedList.AddLast(1);
linkedList.AddLast(2);
linkedList.AddLast(3);
linkedList.AddLast(4);
linkedList.AddLast(5);
  1. 定义一个函数,该函数接受一个整数作为参数,并返回一个布尔值,该布尔值表示该整数是否满足给定条件。
代码语言:csharp
复制
Func<int, bool> condition = x => x % 2 == 0;

在这个例子中,我们定义了一个条件,该条件检查整数是否为偶数。

  1. 使用LINQ查询来查找与给定条件匹配的所有元素,并将它们存储在一个List中。
代码语言:csharp
复制
List<LinkedListNode<int>> nodesToRemove = linkedList.Where(x => condition(x.Value)).ToList();
  1. 遍历List中的每个元素,并从LinkedList中删除它们。
代码语言:csharp
复制
foreach (var node in nodesToRemove)
{
    linkedList.Remove(node);
}

现在,LinkedList中所有与给定条件匹配的元素都已被删除。

完整的代码示例如下:

代码语言:csharp
复制
using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main(string[] args)
    {
        LinkedList<int> linkedList = new LinkedList<int>();
        linkedList.AddLast(1);
        linkedList.AddLast(2);
        linkedList.AddLast(3);
        linkedList.AddLast(4);
        linkedList.AddLast(5);

        Func<int, bool> condition = x => x % 2 == 0;

        List<LinkedListNode<int>> nodesToRemove = linkedList.Where(x => condition(x.Value)).ToList();

        foreach (var node in nodesToRemove)
        {
            linkedList.Remove(node);
        }

        Console.WriteLine("LinkedList after removing elements that match the condition:");
        foreach (var item in linkedList)
        {
            Console.WriteLine(item);
        }
    }
}

输出:

代码语言:txt
复制
LinkedList after removing elements that match the condition:
1
3
5

这个示例中,我们从LinkedList中删除了所有偶数元素。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的结果

领券