Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know if an enumerator has reached the end of the collection in C#?

I am porting a library from C++ to C#. The old library uses vectors from C++ and in the C# I am using generic Dictionaries because they're actually a good data structure for what I'm doing (each element has an ID, then I just use using TypeDictionary = Dictionary<String, Type>;). Now, in the C# code I use a loop like this one

TypeDictionary.Enumerator tdEnum = MyTypeDictionary.GetEnumerator();

while( tdEnum.MoveNext() ) 
{
   Type element = typeElement.Current.Value;

   // More code here
}

to iterate through the elements of the collection. The problem is that in particular cases I need to check if a certain enumerator has reached the end of the collection, in C++ I would have done a check like this:

if ( tdEnum == MyTypeDictionary.end() ) // More code here

But I just don't know how to handle this situation in C#, any ideas?

Thank you
Tommaso

like image 623
tunnuz Avatar asked Apr 26 '10 14:04

tunnuz


People also ask

How does enumerator work in C#?

In the C# language, enum (also called enumeration) is a user-defined value type used to represent a list of named integer constants. It is created using the enum keyword inside a class, structure, or namespace. It improves a program's readability, maintainability and reduces complexity.

What is the return type of MoveNext method of Ienumerator?

If MoveNext passes the end of the collection, the enumerator is positioned after the last element in the collection and MoveNext returns false .


1 Answers

Here's a pretty simple way of accomplishing this.

bool hasNext = tdEnum.MoveNext();
while (hasNext) {
    int i = tdEnum.Current;
    hasNext = tdEnum.MoveNext();
}

I found an online tutorial that also may help you understand how this works.

http://www.c-sharpcorner.com/UploadFile/prasadh/Enumerators11132005232321PM/Enumerators.aspx

like image 83
Robert Greiner Avatar answered Oct 03 '22 07:10

Robert Greiner