<p>What is the best way to iterate through a strongly-typed generic List in C#.NET and VB.NET?</p>

[{'answer_id': 15210, 'author': 'mbillard', 'author_id': 810, 'author_profile': 'https://Stackoverflow.com/users/810', 'pm_score': 6, 'selected': True, 'text': "<p>For C#:</p>\n\n<pre><code>foreach(ObjectType objectItem in objectTypeList)\n{\n    // ...do some stuff\n}\n</code></pre>\n\n<p>Answer for VB.NET from <strong>Purple Ant</strong>:</p>\n\n<pre><code>For Each objectItem as ObjectType in objectTypeList\n    'Do some stuff '\nNext\n</code></pre>\n"}, {'answer_id': 15212, 'author': 'Dan Herbert', 'author_id': 392, 'author_profile': 'https://Stackoverflow.com/users/392', 'pm_score': 1, 'selected': False, 'text': '<p>I may be missing something, but iterating through a generic list should be fairly simple if you use my examples below. The List&lt;> class implements the IList and IEnumerable interfaces so that you can easily iterate through them basically any way you want.</p>\n\n<p>The most efficient way would be to use a for loop:  </p>\n\n<pre><code>for(int i = 0; i &lt; genericList.Count; ++i) \n{\n     // Loop body\n}\n</code></pre>\n\n<p>You may also choose to use a foreach loop:</p>\n\n<pre><code>foreach(&lt;insertTypeHere&gt; o in genericList)\n{\n    // Loop body\n}\n</code></pre>\n'}, {'answer_id': 15218, 'author': 'Brian G Swanson', 'author_id': 1795, 'author_profile': 'https://Stackoverflow.com/users/1795', 'pm_score': 2, 'selected': False, 'text': "<p>For VB.NET:</p>\n\n<p><pre><code>For Each tmpObject as ObjectType in ObjectTypeList\n    'Do some stuff '\nNext</pre></code></p>\n"}, {'answer_id': 15222, 'author': 'Matt Hamilton', 'author_id': 615, 'author_profile': 'https://Stackoverflow.com/users/615', 'pm_score': 2, 'selected': False, 'text': "<p>Without knowing the internal implementation of a list, I think generally the best way to iterate over it would be a foreach loop. Because foreach uses an IEnumerator to walk over the list, it's up to the list itself to determine how to move from object to object.</p>\n\n<p>If the internal implementation was, say, a linked list, then a simple for loop would be quite a bit slower than a foreach.</p>\n\n<p>Does that make sense?</p>\n"}, {'answer_id': 15232, 'author': 'Keith', 'author_id': 905, 'author_profile': 'https://Stackoverflow.com/users/905', 'pm_score': 4, 'selected': False, 'text': '<p>With any generic implementation of IEnumerable the best way is:</p>\n\n<pre><code>//C#\nforeach( var item in listVariable) {\n    //do stuff\n}\n</code></pre>\n\n<p>There is an important exception however. IEnumerable involves an overhead of Current() and MoveNext() that is what the foreach loop is actually compiled into.</p>\n\n<p>When you have a simple array of structs:</p>\n\n<pre><code>//C#\nint[] valueTypeArray;\nfor(int i=0; i &lt; valueTypeArray.Length; ++i) {\n     int item = valueTypeArray[i];\n     //do stuff\n}\n</code></pre>\n\n<p>Is quicker.</p>\n\n<hr>\n\n<p><strong>Update</strong></p>\n\n<p>Following a discussion with @Steven Sudit (see comments) I think my original advice may be out of date or mistaken, so I ran some tests:</p>\n\n<pre><code>// create a list to test with\nvar theList = Enumerable.Range(0, 100000000).ToList();\n\n// time foreach\nvar sw = Stopwatch.StartNew();\nforeach (var item in theList)\n{\n    int inLoop = item;\n}\nConsole.WriteLine("list  foreach: " + sw.Elapsed.ToString());\n\nsw.Reset();\nsw.Start();\n\n// time for\nint cnt = theList.Count;\nfor (int i = 0; i &lt; cnt; i++)\n{\n    int inLoop = theList[i];\n}\nConsole.WriteLine("list  for    : " + sw.Elapsed.ToString());\n\n// now run the same tests, but with an array\nvar theArray = theList.ToArray();\n\nsw.Reset();\nsw.Start();\n\nforeach (var item in theArray)\n{\n    int inLoop = item;\n}\nConsole.WriteLine("array foreach: " + sw.Elapsed.ToString());\n\nsw.Reset();\nsw.Start();\n\n// time for\ncnt = theArray.Length;\nfor (int i = 0; i &lt; cnt; i++)\n{\n    int inLoop = theArray[i];\n}\nConsole.WriteLine("array for    : " + sw.Elapsed.ToString());\n\nConsole.ReadKey();\n</code></pre>\n\n<p>So, I ran this in release with all optimisations:</p>\n\n<pre><code>list  foreach: 00:00:00.5137506\nlist  for    : 00:00:00.2417709\narray foreach: 00:00:00.1085653\narray for    : 00:00:00.0954890\n</code></pre>\n\n<p>And then debug without optimisations:</p>\n\n<pre><code>list  foreach: 00:00:01.1289015\nlist  for    : 00:00:00.9945345\narray foreach: 00:00:00.6405422\narray for    : 00:00:00.4913245\n</code></pre>\n\n<p>So it appears fairly consistent, <code>for</code> is quicker than <code>foreach</code> and arrays are quicker than generic lists.</p>\n\n<p>However, this is across 100,000,000 iterations and the difference is about .4 of a second between the fastest and slowest methods. Unless you\'re doing massive performance critical loops it just isn\'t worth worrying about.</p>\n'}, {'answer_id': 15238, 'author': 'Adam Lassek', 'author_id': 1249, 'author_profile': 'https://Stackoverflow.com/users/1249', 'pm_score': 3, 'selected': False, 'text': '<p>C#</p>\n\n<pre><code>myList&lt;string&gt;().ForEach(\n    delegate(string name)\n    {\n        Console.WriteLine(name);\n    });\n</code></pre>\n\n<p>Anonymous delegates are not currently implemented in VB.Net, but both C# and VB.Net should be able to do lambdas:</p>\n\n<p>C#</p>\n\n<pre><code>myList&lt;string&gt;().ForEach(name =&gt; Console.WriteLine(name));\n</code></pre>\n\n<p>VB.Net</p>\n\n<pre><code>myList(Of String)().ForEach(Function(name) Console.WriteLine(name))\n</code></pre>\n\n<hr>\n\n<p>As Grauenwolf pointed out the above VB won\'t compile since the lambda doesn\'t return a value. A normal ForEach loop as others have suggested is probably the easiest for now, but as usual it takes a block of code to do what C# can do in one line.</p>\n\n<hr>\n\n<p>Here\'s a trite example of why this might be useful: this gives you the ability to pass in the loop logic from another scope than where the IEnumerable exists, so you don\'t even have to expose it if you don\'t want to.</p>\n\n<p>Say you have a list of relative url paths that you want to make absolute:</p>\n\n<pre><code>public IEnumerable&lt;String&gt; Paths(Func&lt;String&gt; formatter) {\n    List&lt;String&gt; paths = new List&lt;String&gt;()\n    {\n        "/about", "/contact", "/services"\n    };\n\n    return paths.ForEach(formatter);\n}\n</code></pre>\n\n<p>So then you could call the function this way:</p>\n\n<pre><code>var hostname = "myhost.com";\nvar formatter = f =&gt; String.Format("http://{0}{1}", hostname, f);\nIEnumerable&lt;String&gt; absolutePaths = Paths(formatter);\n</code></pre>\n\n<p>Giving you <code>"http://myhost.com/about", "http://myhost.com/contact"</code> etc. Obviously there are better ways to accomplish this in this specfic example, I\'m just trying to demonstrate the basic principle.</p>\n'}, {'answer_id': 15527, 'author': 'jfs', 'author_id': 718, 'author_profile': 'https://Stackoverflow.com/users/718', 'pm_score': 2, 'selected': False, 'text': '<p>It depends on your application:</p>\n\n<ul>\n<li>for loop, if efficiency is a priority</li>\n<li>foreach loop or ForEach method, whichever communicates your intent more clearly</li>\n</ul>\n'}]
['https://Stackoverflow.com/questions/15204', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1224/']