9

I have created a data structure consisting of intervals. The data structure should naturally have an enumerator that enumerates all intervals, but I would like to expose two different enumerators that enumerate the intervals in different order.

One of the enumerators enumerate the intervals really fast, but in somewhat arbitrary order. The other enumerates them in lexicographical order, but a bit slower (depends on the intervals though). Depending on what you try to achieve, one enumerator might be to prefer over the other.

Is there a way to allow the user to decide which enumerator should be used in a foreach loop for instance? If not, I could easily have a property used for switching between the enumerators, or the constructor could take an additional parameter. But I'm a bit afraid that it will cause more confusion than convenience.

Should I rather, for the other enumerator, make a separate method that returns an IEnumerator? Is there a best practice for this little odd problem?

Mikkel R. Lund
  • 2,336
  • 1
  • 31
  • 44

1 Answers1

15

Exposing two properties which return different enumerators is probably the right way to go. Instead of your data structure implementing IEnumerable itself (I'm guessing with that one), create two different IEnumerator implementations, and have a propery exposed from the main class for each one. Then the using code is straightforward:

foreach( var item in data.FastEnumerator )
{
    ....

foreach( var item in data.LexicalEnumerator )
{
    ....
SteveLove
  • 3,137
  • 15
  • 17
  • Brilliant idea! Really like it :) As the data structure is part of the C5 Generic Collections Library it has to implement IEnumerable. I've made the collection's normal enumerator the fast, 'unsorted' version. The sorted version is exposed through the method GetEnumeratorSorted and the property Sorted, so the collection can be enumerated in a loop like 'foreach (var interval in collection.Sorted) {}'. Works like a charm :D – Mikkel R. Lund Jul 20 '13 at 19:42
  • 2
    You cannot use a foreach on an IEnumerator as it requires a IEnumerable simply for the expected GetEnumerator method. – Asher G. Oct 06 '17 at 00:26