Search code examples
c#linqgenericscollections

How do I convert a recursive object to a Collection in C#?


I have a recursive object, a linked list really:

public class LinkedList 
{
    public string UniqueKey { get; set; }
    public LinkedList LinkedList { get; set; }
}

LinkedList will have some object graph that will eventually end in LinkedList.LinkedList == null.

I would like to take all the objects in the graph and put them into a LinkedList collection so that I can iterate over them. How do I do this in C#? I feel as if there's a really easy way of going about this using yield or Linq voodoo?


Solution

  • Something like this should work. If you have control over the class you can make it IEnumerable directly.

    public class LinkedListEnumerable : IEnumerable<string>
    {
        LinkedList list;
        public LinkedListEnumerable(LinkedList l)
        {
            this.list = l;
        }
    
        public IEnumerator<string> GetEnumerator()
        {
            LinkedList l = list;
            while(l != null)
            {
                yield return l.UniqueKey;
                l = l.Next;
            }
        }
    }
    

    Then you can iterate over LinkedListEnumerable with a for-each loop.