Search code examples
c#listcopyclonelazy-evaluation

Lazy list clone


I have a List with a large amount of elements in it. I need to create a copy of this list to perform operations on it without altering the original list. However, the operations typically only access a small proportion of the elements of the list, and so it is inefficient to copy the entire thing when most of it will go unused. Is there a simple way to create an object which is a clone of a list, but only clones elements when they are accessed? I have looked into the Lazy<T> class, which seems to be what I want, but I don't know how to apply it in this situation.

I want to be able to do something like this:

LazyListCopy<SomeType> lazyCopy = LazyListCopy.Copy(myList); // No elements have been copied at this point
DoSomethingWith(lazyCopy[34]);                               // 35th element has now been copied

And this:

foreach(SomeType listElement in LazyCopy.Copy(myOtherList))
{
    if (!Check(listElement))   // Object corresponding to listElement has been cloned
        break;
}

I don't mind if the solution isn't generic enough to handle Lists of any type; I would be fine with it being specific to one or two classes I've created.

Preferably this would be a deep copy rather than a shallow copy, but a shallow copy would still be useful, and I would appreciate examples of that if it is shorter/simpler too.


Solution

  • Sounds like you want to end up with your original list plus a sparse collection of overrides.

    Why not create a dictionary for the overrides, keyed on the index into the original list? You can then manually add values from your original list as they are needed.

    You could wrap this functionality up into a class that wraps IList<T> if it's something you're going to use often.