I have a Java code block like following:

Vector<NameAddress> route = dialog.getRoute(); 
for ( Enumeration<NameAddress> e = route.elements(); e.hasMoreElements(); ) {
    // some more to copy route to another Vector<>
    }

I am trying to convert it in C# and here is my code:

List<NameAddress> route = dialog.getRoute();
for ( IEnumerable<NameAddress> e = route.All; e.hasMoreElements(); ) {
    // some more to copy route to another List<>
    }

How can I solve the Enumeration part in c# ?

Dani AI

Generated

Short answer: Java's Enumeration<T> maps to C#'s IEnumerator<T> (and, idiomatically, you use IEnumerable<T> with a foreach). is correct that foreach is the simplest approach. If you want a one‑to‑one mapping of the Enumeration methods (hasMoreElements/nextElement), use the enumerator's MoveNext()/Current.

A direct equivalent using the enumerator looks like this:

var source = dialog.GetRoute();        // an IEnumerable<NameAddress>
using (var en = source.GetEnumerator())
{
    while (en.MoveNext())
    {
        var item = en.Current;
        // copy or process item
        dest.Add(item);
    }
}

Faster/simpler copying options you can use instead of manual enumeration:

var copy1 = new List<NameAddress>(source);   // constructor copies the sequence
var copy2 = source.ToList();                 // needs using System.Linq
dest.AddRange(source);                       // append all elements to an existing list

A few practical notes and gotchas that answers above don't fully mention:

  • IEnumerable<T> is the sequence interface; IEnumerator<T> is the iterator (the thing with MoveNext/Current). route.All and hasMoreElements() are not C# patterns.
  • List<T> is not synchronized like Java's Vector. If thread safety mattered in the Java code, protect the list with a lock or use the concurrent collections in System.Collections.Concurrent.
  • Copy constructors and AddRange perform a shallow copy of references. For deep copies you must clone each element.
  • Modifying a collection while enumerating will typically throw an exception; collect removals separately or iterate a snapshot if you need to change the source while walking it.

These points should cover both the idiomatic C# way and a direct method-level equivalent to Java's Enumeration.

Use can use a foreach for all IEnumerables (like List)

List<NameAddress> route = dialog.getRoute();
foreach(NameAddress nameAddress in route)
{
    //some more to copy rout to another List<>
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.