1
我有兩個LinkedLists,我想將所有匹配LinkedListA的條件的元素移動到LinkedListB(LinkedListB不是空的,以此開始)。有任何想法嗎?如何根據標準將元素從一個LinkedList移動到另一個LinkedList
我有兩個LinkedLists,我想將所有匹配LinkedListA的條件的元素移動到LinkedListB(LinkedListB不是空的,以此開始)。有任何想法嗎?如何根據標準將元素從一個LinkedList移動到另一個LinkedList
如果你從列表中移動到列表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);
將他們在哪裏?到最後? – mquander 2009-04-30 16:50:41
訂單無關緊要 – 2009-04-30 16:53:47