Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<blockquote> <p>I am trying to convert it in C# and here is my buggy code:</p> </blockquote> <p>It would be more useful if you described in what way your code is buggy, but I have a somewhat different question:</p> <p><strong>Why are you copying the items manually in the first place?</strong></p> <p>If you simply want to copy the items from one collection to another, <code>List&lt;T&gt;</code> offers a constructor <a href="http://msdn.microsoft.com/en-us/library/fkbw11z0.aspx" rel="nofollow"><code>List&lt;T&gt;(IEnumerable&lt;T&gt;)</code></a> which does exactly what you want: copies the items from the source collection to the newly created collection.</p> <p>That replaces your code</p> <pre><code>List&lt;NameAddress&gt; route = dialog.getRoute(); for ( IEnumerable&lt;NameAddress&gt; e = route.All; e.hasMoreElements(); ) { // some more to copy route to another List&lt;&gt; } </code></pre> <p>with the much shorter</p> <pre><code>List&lt;NameAddress&gt; newRoute = new List&lt;NameAddress&gt;(dialog.getRoute()); </code></pre> <p>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.</p> <p>With <code>IEnumerable&lt;T1&gt; dialog.getRoute()</code> and <code>List&lt;T2&gt;</code>, the only requirement is that there exists a possible implicit conversion from T1 to T2. You can <a href="http://msdn.microsoft.com/en-us/library/aa288476%28v=vs.71%29.aspx" rel="nofollow">define your own conversion</a>, if the framework does not understand how to map between the types.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload