Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple Enumerators for a Single C# Class

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?

like image 789
Mikkel R. Lund Avatar asked Jul 20 '13 07:07

Mikkel R. Lund


1 Answers

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 )
{
    ....
like image 105
SteveLove Avatar answered Oct 20 '22 00:10

SteveLove