要从C#中的LinkedList中删除与给定条件匹配的元素,您可以使用以下步骤:
using System.Collections.Generic;
using System.Linq;
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);
}
现在,LinkedList中所有与给定条件匹配的元素都已被删除。
完整的代码示例如下:
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);
}
}
}
输出:
LinkedList after removing elements that match the condition:
1
3
5
这个示例中,我们从LinkedList中删除了所有偶数元素。
领取专属 10元无门槛券
手把手带您无忧上云