tags:

views:

97

answers:

1

I have two LinkedLists, I'd like to move all elements which match some criteria from LinkedListA to LinkedListB (LinkedListB is not empty to start with). Any ideas?

+2  A: 

If you're moving from list a to the end of list b, try this method:

// .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);

or as an extension method:

// .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);
Michael Meadows
Would this work: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)) { first.Remove(current); second.AddLast(current); } current = next; }}
cskilbeck
@cskilbeck, I'm not sure. The question is if the overloaded AddLast method of LinkedList<T> includes the Next and Previous nodes. If it does, then you'd be copying the entire chain instead of just the value.
Michael Meadows
Just verified, changing second.AddLast(current.Value); to second.AddLast(current); behaves the same, so they both work.
Michael Meadows
brilliant, thanks so much for your help
cskilbeck