Search code examples
c#concatenationenumerator

Is there combo enumerator ready to use?


I have in my class have two collections for which I have working GetEnumerator method. I would like to provide GetEnumerator for my class as well in such sense, that first goes enumeration after first collection and then for the second.

Is there ready to use some ComboEnumerator class in C#?

Little background for curious minds -- first collection comes from my implementation of Dictionary, second collection is really just a single element, optional, wrapped in array. And the class I would like to provide enumerator for, is NullDictionary derived from the first Dictionary. So I am looking for:

public override IEnumerator<KeyValuePair<K, V>> GetEnumerator()
{
    if (nullValue.HasValue)
        return ComboEnumerator.Create(
            new []{new KeyValuePair<K, V>(null, nullValue.Value)}.GetEnumerator(),
                base.GetEnumerator());
    else
        return base.GetEnumerator();
}

Update: I have my own implementation, this is not a question "how to implement XYZ".


Solution

  • I think this method that you are looking for does not exist. If you just want to enumerate the two collections in the standard way (returns each item of the first collection and then the same for the second one) I think you can use the Enumerable.Concat extension method. I don't see how you can do it in a more performant way.
    You can see the Enumerable.Concat method implementation

    If you want to enumerate the collections in a non standard way (there are multiple ways to enumerate these two collections) I think you are the only that can do it, the .net framework can not provide an implementation for each way to enumerate two collections.