<p>I frequently find myself writing code like this:</p>

<pre><code>List&lt;int&gt; list = new List&lt;int&gt; { 1, 3, 5 };
foreach (int i in list) {
    Console.Write("{0}\t", i.ToString()); }
Console.WriteLine();
</code></pre>

<p>Better would be something like this:</p>

<pre><code>List&lt;int&gt; list = new List&lt;int&gt; { 1, 3, 5 };
Console.WriteLine("{0}\t", list);
</code></pre>

<p>I suspect there's some clever way of doing this, but I don't see it. Does anybody have a better solution than the first block? </p>

[{'answer_id': 52940, 'author': 'Jason Bunting', 'author_id': 1790, 'author_profile': 'https://Stackoverflow.com/users/1790', 'pm_score': 8, 'selected': True, 'text': '<p>Do this:</p>\n\n<pre><code>list.ForEach(i =&gt; Console.Write("{0}\\t", i));\n</code></pre>\n\n<hr>\n\n<p>EDIT: To others that have responded - he wants them all on the same line, with tabs between them. :)</p>\n'}, {'answer_id': 52941, 'author': 'John Boker', 'author_id': 2847, 'author_profile': 'https://Stackoverflow.com/users/2847', 'pm_score': 2, 'selected': False, 'text': '<pre><code>        List&lt;int&gt; a = new List&lt;int&gt;() { 1, 2, 3, 4, 5 };\n        a.ForEach(p =&gt; Console.WriteLine(p));\n</code></pre>\n\n<p>edit: ahhh he beat me to it.</p>\n'}, {'answer_id': 52942, 'author': 'Mark Cidade', 'author_id': 1659, 'author_profile': 'https://Stackoverflow.com/users/1659', 'pm_score': 2, 'selected': False, 'text': '<pre><code>list.ForEach(x=&gt;Console.WriteLine(x));\n</code></pre>\n'}, {'answer_id': 52960, 'author': 'George Mauer', 'author_id': 5056, 'author_profile': 'https://Stackoverflow.com/users/5056', 'pm_score': 2, 'selected': False, 'text': '<pre><code>List&lt;int&gt; list = new List&lt;int&gt; { 1, 3, 5 };\nlist.ForEach(x =&gt; Console.WriteLine(x));\n</code></pre>\n\n<p>Edit: Dammit! took too long to open visual studio to test it.</p>\n'}, {'answer_id': 52972, 'author': 'Vinko Vrsalovic', 'author_id': 5190, 'author_profile': 'https://Stackoverflow.com/users/5190', 'pm_score': 5, 'selected': False, 'text': '<p>A different approach, just for kicks:</p>\n\n<pre><code>Console.WriteLine(string.Join("\\t", list));\n</code></pre>\n'}, {'answer_id': 65692, 'author': 'Amy B', 'author_id': 8155, 'author_profile': 'https://Stackoverflow.com/users/8155', 'pm_score': 0, 'selected': False, 'text': '<pre><code>public static void WriteLine(this List&lt;int&gt; theList)\n{\n  foreach (int i in list)\n  {\n    Console.Write("{0}\\t", t.ToString());\n  }\n  Console.WriteLine();\n}\n</code></pre>\n\n<p>Then, later...</p>\n\n<pre><code>list.WriteLine();\n</code></pre>\n'}, {'answer_id': 767963, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<pre><code>new List&lt;int&gt; { 1, 3, 5 }.ForEach(Console.WriteLine);\n</code></pre>\n'}, {'answer_id': 949955, 'author': 'Ed Sykes', 'author_id': 98551, 'author_profile': 'https://Stackoverflow.com/users/98551', 'pm_score': 2, 'selected': False, 'text': '<p>If there is a piece of code that you repeat all the time according to Don\'t Repeat Yourself you should put it in your own library and call that. With that in mind there are 2 aspects to getting the right answer here. The first is clarity and brevity in the code that calls the library function. The second is the performance implications of foreach. </p>\n\n<p>First let\'s think about the clarity and brevity in the calling code. </p>\n\n<p>You can do foreach in a number of ways:</p>\n\n<ol>\n<li>for loop</li>\n<li>foreach loop</li>\n<li>Collection.ForEach</li>\n</ol>\n\n<p>Out of all the ways to do a foreach List.ForEach with a lamba is the clearest and briefest.</p>\n\n<pre><code>list.ForEach(i =&gt; Console.Write("{0}\\t", i));\n</code></pre>\n\n<p>So at this stage it may look like the List.ForEach is the way to go. However what\'s the performance of this? It\'s true that in this case the time to write to the console will govern the performance of the code. When we know something about performance of a particular language feature we should certainly at least consider it.</p>\n\n<p>According to <a href="http://diditwith.net/2006/10/05/PerformanceOfForeachVsListForEach.aspx" rel="nofollow noreferrer">Duston Campbell\'s performance measurements of foreach</a> the fastest way of iterating the list under optimised code is using a for loop without a call to List.Count.</p>\n\n<p>The for loop however is a verbose construct. It\'s also seen as a very iterative way of doing things which doesn\'t match with the current trend towards functional idioms.</p>\n\n<p>So can we get brevity, clarity and performance? We can by using an extension method. In an ideal world we would create an extension method on Console that takes a list and writes it with a delimiter. We can\'t do this because Console is a static class and extension methods only work on instances of classes. Instead we need to put the extension method on the list itself (as per David B\'s suggestion):</p>\n\n<pre><code>public static void WriteLine(this List&lt;int&gt; theList)\n{\n  foreach (int i in list)\n  {\n    Console.Write("{0}\\t", t.ToString());\n  }\n  Console.WriteLine();\n}\n</code></pre>\n\n<p>This code is going to used in many places so we should carry out the following improvements:</p>\n\n<ul>\n<li>Instead of using foreach we should use the fastest way of iterating the collection which is a for loop with a cached count. </li>\n<li>Currently only List can be passed as an argument. As a library function we can generalise it through a small amount of effort. </li>\n<li>Using List limits us to just Lists, Using IList allows this code to work with Arrays too.</li>\n<li>Since the extension method will be on an IList we need to change the name to make it clearer what we are writing to:</li>\n</ul>\n\n<p>Here\'s how the code for the function would look:</p>\n\n<pre><code>public static void WriteToConsole&lt;T&gt;(this IList&lt;T&gt; collection)\n{\n    int count = collection.Count();\n    for(int i = 0;  i &lt; count; ++i)\n    {\n        Console.Write("{0}\\t", collection[i].ToString(), delimiter);\n    }\n    Console.WriteLine();\n}\n</code></pre>\n\n<p>We can improve this even further by allowing the client to pass in the delimiter. We could then provide a second function that writes to console with the standard delimiter like this:</p>\n\n<pre><code>public static void WriteToConsole&lt;T&gt;(this IList&lt;T&gt; collection)\n{\n    WriteToConsole&lt;T&gt;(collection, "\\t");\n}\n\npublic static void WriteToConsole&lt;T&gt;(this IList&lt;T&gt; collection, string delimiter)\n{\n    int count = collection.Count();\n    for(int i = 0;  i &lt; count; ++i)\n    {\n         Console.Write("{0}{1}", collection[i].ToString(), delimiter);\n    }\n    Console.WriteLine();\n}\n</code></pre>\n\n<p>So now, given that we want a brief, clear performant way of writing lists to the console we have one. Here is entire source code including a demonstration of using the the library function:</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace ConsoleWritelineTest\n{\n    public static class Extensions\n    {\n        public static void WriteToConsole&lt;T&gt;(this IList&lt;T&gt; collection)\n        {\n            WriteToConsole&lt;T&gt;(collection, "\\t");\n        }\n\n        public static void WriteToConsole&lt;T&gt;(this IList&lt;T&gt; collection, string delimiter)\n        {\n            int count = collection.Count();\n            for(int i = 0;  i &lt; count; ++i)\n            {\n                Console.Write("{0}{1}", collection[i].ToString(), delimiter);\n            }\n            Console.WriteLine();\n        }\n    }\n\n    internal class Foo\n    {\n        override public string ToString()\n        {\n            return "FooClass";\n        }\n    }\n\n    internal class Program\n    {\n\n        static void Main(string[] args)\n        {\n            var myIntList = new List&lt;int&gt; {1, 2, 3, 4, 5};\n            var myDoubleList = new List&lt;double&gt; {1.1, 2.2, 3.3, 4.4};\n            var myDoubleArray = new Double[] {12.3, 12.4, 12.5, 12.6};\n            var myFooList = new List&lt;Foo&gt; {new Foo(), new Foo(), new Foo()};\n            // Using the standard delimiter /t\n            myIntList.WriteToConsole();\n            myDoubleList.WriteToConsole();\n            myDoubleArray.WriteToConsole();\n            myFooList.WriteToConsole();\n            // Using our own delimiter ~\n            myIntList.WriteToConsole("~");\n            Console.Read();\n        }\n    }\n}\n</code></pre>\n\n<p>=======================================================</p>\n\n<p>You might think that this should be the end of the answer. However there is a further piece of generalisation that can be done. It\'s not clear from fatcat\'s question if he is always writing to the console. Perhaps something else is to be done in the foreach. In that case Jason Bunting\'s answer is going to give that generality. Here is his answer again:</p>\n\n<pre><code>list.ForEach(i =&gt; Console.Write("{0}\\t", i));\n</code></pre>\n\n<p>That is unless we make one more refinement to our extension methods and add FastForEach as below:</p>\n\n<pre><code>public static void FastForEach&lt;T&gt;(this IList&lt;T&gt; collection, Action&lt;T&gt; actionToPerform)\n    {\n        int count = collection.Count();\n        for (int i = 0; i &lt; count; ++i)\n        {\n            actionToPerform(collection[i]);    \n        }\n        Console.WriteLine();\n    }\n</code></pre>\n\n<p><strong>This allows us to execute any arbitrary code against every element in the collection <em>using the fastest possible iteration method</em>.</strong></p>\n\n<p>We can even change the WriteToConsole function to use FastForEach</p>\n\n<pre><code>public static void WriteToConsole&lt;T&gt;(this IList&lt;T&gt; collection, string delimiter)\n{\n     collection.FastForEach(item =&gt; Console.Write("{0}{1}", item.ToString(), delimiter));\n}\n</code></pre>\n\n<p>So now the entire source code, including an example usage of FastForEach is:</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace ConsoleWritelineTest\n{\n    public static class Extensions\n    {\n        public static void WriteToConsole&lt;T&gt;(this IList&lt;T&gt; collection)\n        {\n            WriteToConsole&lt;T&gt;(collection, "\\t");\n        }\n\n        public static void WriteToConsole&lt;T&gt;(this IList&lt;T&gt; collection, string delimiter)\n        {\n             collection.FastForEach(item =&gt; Console.Write("{0}{1}", item.ToString(), delimiter));\n        }\n\n        public static void FastForEach&lt;T&gt;(this IList&lt;T&gt; collection, Action&lt;T&gt; actionToPerform)\n        {\n            int count = collection.Count();\n            for (int i = 0; i &lt; count; ++i)\n            {\n                actionToPerform(collection[i]);    \n            }\n            Console.WriteLine();\n        }\n    }\n\n    internal class Foo\n    {\n        override public string ToString()\n        {\n            return "FooClass";\n        }\n    }\n\n    internal class Program\n    {\n\n        static void Main(string[] args)\n        {\n            var myIntList = new List&lt;int&gt; {1, 2, 3, 4, 5};\n            var myDoubleList = new List&lt;double&gt; {1.1, 2.2, 3.3, 4.4};\n            var myDoubleArray = new Double[] {12.3, 12.4, 12.5, 12.6};\n            var myFooList = new List&lt;Foo&gt; {new Foo(), new Foo(), new Foo()};\n\n            // Using the standard delimiter /t\n            myIntList.WriteToConsole();\n            myDoubleList.WriteToConsole();\n            myDoubleArray.WriteToConsole();\n            myFooList.WriteToConsole();\n\n            // Using our own delimiter ~\n            myIntList.WriteToConsole("~");\n\n            // What if we want to write them to separate lines?\n            myIntList.FastForEach(item =&gt; Console.WriteLine(item.ToString()));\n            Console.Read();\n        }\n    }\n}\n</code></pre>\n'}, {'answer_id': 15260381, 'author': 'Lev Lukomsky', 'author_id': 406642, 'author_profile': 'https://Stackoverflow.com/users/406642', 'pm_score': 1, 'selected': False, 'text': '<p>Also you can do join:</p>\n\n<pre><code>var qwe = new List&lt;int&gt; {5, 2, 3, 8};\nConsole.WriteLine(string.Join("\\t", qwe));\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/52927', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4593/']