0

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 buggy 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# ?

mesbahuk
  • 268
  • 1
  • 2
  • 10
  • 1
    `Vector` and `Enumeration`? How old is your Java code? Why not `List` and `Iterator`? – fge Jul 17 '13 at 07:18
  • You should always use the foreach loop while working in C#. This implicitly works on IEnumerbale's GetEnumerator() method and gets you the value desired. Also make use of var keyword whenever possible. This is a good feature of c# which makes it hybrid lang. dynamic as well as staic typed. – Ankur Sharma Jul 17 '13 at 07:22
  • @AnkurSharma `var` does not make C# dynamically typed at all. Do not confuse `var` with either VB's `Variant` or Javascript's `var`; `var` in C# is used for *type inferrence*, not *dynamic typing*. The difference is similar to that of a Ferrari and an electric wheel chair. There's [dynamic](http://msdn.microsoft.com/en-us/library/vstudio/dd264741.aspx) and there's [var](http://msdn.microsoft.com/en-us/library/bb383973.aspx). – user Jul 17 '13 at 07:35
  • (1) you do not need to use a loop to copy to another List. Check List.AddRange (2) you do not need to build a `for` loop manually, try `foreach`ing (3) if you need to loop manually, try using `list.GetEnumerator()`, it will return you a `IEnumerator` which is the closest possible translation of `Enumeration` from Java – quetzalcoatl Jul 17 '13 at 08:26
  • @MichaelKjörling : Voting down my answer wouldn't solve your purpose. First read the latest specification of C# 5.0 and then comment. Read: http://stackoverflow.com/questions/1347657/php-variable-variables-in-net The .net framework makes use of dynamic language runtime. using var it helps to dynamically type the code. Javascirpt's var is also used for type inference. – Ankur Sharma Jul 17 '13 at 11:15
  • @AnkurSharma **I have not voted down any current answer on this question.** Not yours nor anyone else's. – user Jul 17 '13 at 11:24
  • @fge this java project was written in java 1.2, & my boss wants this to be ported in .NET – mesbahuk Jul 30 '13 at 07:05

4 Answers4

3
List<string> names = dialog.GetNames();
foreach(string name in names)
{
}

But you should read this too Performance difference for control structures 'for' and 'foreach' in C#

Community
  • 1
  • 1
user743414
  • 861
  • 10
  • 20
1

List implements IEnumerable so you can do it like this:

List<NameAddress> route = dialog.getRoute();
foreach (var e in route) 
{

}
gzaxx
  • 16,281
  • 2
  • 31
  • 53
1

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

It would be more useful if you described in what way your code is buggy, but I have a somewhat different question:

Why are you copying the items manually in the first place?

If you simply want to copy the items from one collection to another, List<T> offers a constructor List<T>(IEnumerable<T>) which does exactly what you want: copies the items from the source collection to the newly created collection.

That replaces your code

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

with the much shorter

List<NameAddress> newRoute = new List<NameAddress>(dialog.getRoute());

Since MSDN states that the constructor is an O(n) operation, it almost certainly does the same kind of iteration under the hood, but instead of writing it yourself you take advantage of it already having been written as a part of the framework. Copying items from one list to another is a really common operation.

With IEnumerable<T1> dialog.getRoute() and List<T2>, the only requirement is that there exists a possible implicit conversion from T1 to T2. You can define your own conversion, if the framework does not understand how to map between the types.

user
  • 6,669
  • 7
  • 39
  • 77
  • One of the possible reasons for why he does 'copy' the items from one to the other is that .. the other target list may **already exist** and have some older items. In that case, simple `AddRange` would solve the problem. In all other cases, your suggestion is OK, or might be shortened with linq's extensions to `List newRoutes = dialog.getRoute().ToList()`, but that's of course just cosmetics and your explicit example is better for the purposes of explanation. – quetzalcoatl Jul 17 '13 at 08:34
  • 1
    @quetzalcoatl Good point about copying into an existing `List<>` instance. Another reason why I didn't go with the Linq extension methods (which have been exemplified numerous times in answers to this very question) is that the above code should work in *any* version of C# and .NET, which may be a concern. – user Jul 17 '13 at 08:59
-1

use a foreach loop

foreach(var x in route)
{

}
Ankur Sharma
  • 273
  • 2
  • 11
  • 1
    Why would a foreach loop be better than a for loop? What are the considerations involved? In what situations might a foreach loop *not* be a good choice? An answer that explains the *why* is significantly more useful (to both the OP as well as future visitors) than one that simply states an absolute "this is better" with no reasoning, explanation or rationale behind it. [Good advice comes with a rationale so you can tell when it becomes bad advice](http://blogs.msdn.com/b/oldnewthing/archive/2009/11/04/9917052.aspx). – user Jul 17 '13 at 07:52
  • @MichaelKjörling The reason that i said its better because he should make use of the features offered by this language. By "Better" i mean he should use the advantage of this language. What is the use when such feature is given. For loop is much faster than foreach - no doubt in that but the only reason i said it was that it would have become more easy for the OP – Ankur Sharma Jul 17 '13 at 11:04
  • @MichaelKjörling: Voting down wouldn't solve your purpose. First understand what i mean. The others have also stated the same answer. – Ankur Sharma Jul 17 '13 at 11:16
  • **I did not vote this down**, but very nearly did because of the accusation. – user Jul 17 '13 at 11:23
  • @MichaelKjörling: Ok man. Thanks for the suggestion. Next time i would be more precise in choosing my words. – Ankur Sharma Jul 17 '13 at 11:26
  • "For loop is much faster than foreach" - citation needed, as [that claim is contradicted elsewhere](http://stackoverflow.com/questions/1124753/performance-difference-for-control-structures-for-and-foreach-in-c-sharp#comment11984917_1124936). Also, if you need the item index for some reason, foreach is *worse* because then you likely need to loop through the list yet again to find the index of the item you are currently processing, or you need to keep track of the index separately. – user Jul 17 '13 at 11:29
  • You don't necessarily need to be "more precise", but you should *explain the rationale* behind your answer. For example, compare [gzaxx's answer](http://stackoverflow.com/a/17693527/486504) which doesn't claim better or worse, it simply says that it *can* be done with a foreach loop. If one construct was *always* better than another, there would be no need to have both. Sometimes `for()` is more appropriate, at other times `foreach()` fits the bill better. – user Jul 17 '13 at 11:31
  • @MichaelKjörling : http://www.codeproject.com/Articles/6759/FOREACH-Vs-FOR-C I just read about it on code project. So, i just thought that foreach is a little slow to process than the for loop. Thanks for rectifying me. – Ankur Sharma Jul 17 '13 at 11:57
  • The code (for and foreach loops) used in that article *isn't equivalent*. The exact mapping from IL to machine language is machine-dependent and JIT-dependent. Fewer machine code instructions don't *necessarily* (though often do) translate to faster execution. Hence the article is meaningless on anything other than the author's particular system at that time. – user Jul 17 '13 at 12:04
  • @MichaelKjörling: I do not agree with you on this point. If you think this is wrong then you better write it to the OP of this article. – Ankur Sharma Jul 17 '13 at 12:16
  • This stopped being constructive sometime around the third comment, and I am not going to continue this discussion here. Bottom line, I asked for something to support a claim you made (that a for loop is faster than a foreach), you provided it and even a cursory glance through it highlighted multiple issues. Your answer also still doesn't clarify when foreach would be better than a for loop, which was the point of the request in my original comment and a likely reason for the downvote you have received. – user Jul 17 '13 at 12:19