我有两个LinkedLists,我想将所有匹配某些条件的元素从LinkedListA移动到LinkedListB(LinkedListB不是空的开头)。有什么想法吗?
答案 0 :(得分:2)
如果您要从列表a移到列表b的末尾,请尝试以下方法:
// .Net 2.0 compatable
private static void moveFromFirstToSecond<T>(Predicate<T> match, LinkedList<T> first, LinkedList<T> second)
{
LinkedListNode<T> current = first.First;
while (current != null)
{
LinkedListNode<T> next = current.Next;
if (match(current.Value))
{
second.AddLast(current.Value); // second.AddLast(current) also works
first.Remove(current);
}
current = next;
}
}
// for strings that start with "W"
LinkedList<string> a = ...
LinkedList<string> b = ...
moveFromFirstToSecond(delegate(string toMatch)
{ return toMatch.StartsWith("W"); }, a, b);
或作为扩展方法:
// .Net 3.5 or later
public static void MoveMatches<T>(this LinkedList<T> first, Predicate<T> match, LinkedList<T> other)
{
LinkedListNode<T> current = first.First;
while (current != null)
{
LinkedListNode<T> next = current.Next;
if (match(current.Value))
{
other.AddLast(current.Value); // other.AddLast(current) also works
first.Remove(current);
}
current = next;
}
}
// for strings that start with "W"
LinkedList<string> a = ...
LinkedList<string> b = ...
a.MoveMatches(x => x.StartsWith("W"), b);