Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>As you want to "Create a CSV export" from a list of objects, you should be using reflection to work out the columns. </p> <h2>Latest update 12 Feb 2016:</h2> <p>It makes more sense to have the delimiter default to a comma, and useful to make the output of an initial header row optional. It also now supports both <em>fields</em> and <em>simple properties</em> by use of <code>Concat</code>:</p> <pre><code>public static IEnumerable&lt;string&gt; ToCsv&lt;T&gt;(IEnumerable&lt;T&gt; objectlist, string separator = ",", bool header = true) { FieldInfo[] fields = typeof(T).GetFields(); PropertyInfo[] properties = typeof(T).GetProperties(); if (header) { yield return String.Join(separator, fields.Select(f =&gt; f.Name).Concat(properties.Select(p=&gt;p.Name)).ToArray()); } foreach (var o in objectlist) { yield return string.Join(separator, fields.Select(f=&gt;(f.GetValue(o) ?? "").ToString()) .Concat(properties.Select(p=&gt;(p.GetValue(o,null) ?? "").ToString())).ToArray()); } } </code></pre> <p><strong>so you then use it like this for comma delimited:</strong></p> <pre><code>foreach (var line in ToCsv(objects)) { Console.WriteLine(line); } </code></pre> <p><strong>or like this for another delimiter (e.g. TAB):</strong></p> <pre><code>foreach (var line in ToCsv(objects, "\t")) { Console.WriteLine(line); } </code></pre> <h2>Practical examples</h2> <p><strong>write list to a comma-delimited CSV file</strong></p> <pre><code>using (TextWriter tw = File.CreateText("C:\testoutput.csv")) { foreach (var line in ToCsv(objects)) { tw.WriteLine(line); } } </code></pre> <p><strong>or write it tab-delimited</strong></p> <pre><code>using (TextWriter tw = File.CreateText("C:\testoutput.txt")) { foreach (var line in ToCsv(objects, "\t")) { tw.WriteLine(line); } } </code></pre> <p><em>If you have complex fields/properties you will need to filter them out of the select clauses.</em></p> <hr> <h1>Previous updates</h1> <h2>Final thoughts <em>first</em> (so it is not missed):</h2> <p><strong>If you prefer a generic solution (this ensures the objects are of the same type):</strong></p> <pre><code>public static IEnumerable&lt;string&gt; ToCsv&lt;T&gt;(string separator, IEnumerable&lt;T&gt; objectlist) { FieldInfo[] fields = typeof(T).GetFields(); PropertyInfo[] properties = typeof(T).GetProperties(); yield return String.Join(separator, fields.Select(f =&gt; f.Name).Union(properties.Select(p=&gt;p.Name)).ToArray()); foreach (var o in objectlist) { yield return string.Join(separator, fields.Select(f=&gt;(f.GetValue(o) ?? "").ToString()) .Union(properties.Select(p=&gt;(p.GetValue(o,null) ?? "").ToString())).ToArray()); } } </code></pre> <p>This one includes both public fields and public properties.</p> <p><strong>In general with reflection you do not need to know the type of objects in the list (you just must assume they are all the same type).</strong> </p> <p>You could just use:</p> <pre><code>public IEnumerable&lt;object&gt; AnyList { get; set; } </code></pre> <p>The basic process for what you want to do goes something like:</p> <ul> <li>Obtain the type from the first object in the list (e.g. <code>GetType()</code>).</li> <li>Iterate the properties of that type.</li> <li>Write out the CSV header, e.g. based on the names of the property (or an attribute).</li> <li>For each item in the list... <ul> <li>Iterate the properties of that type</li> <li>Get the value for each property (as an object)</li> <li>Write out the ToString() version of the object with delimiters</li> </ul></li> </ul> <p>You can use the same algorithm to generate a 2D array (i.e. if you want the control to display something like CSV in tabular/grid form).</p> <p>The only issue you than have may be converting from IEnumerables/lists of specific types to an IEnumerable. In these instances just use <code>.Cast&lt;object&gt;</code> on your specific typed enumerable.</p> <h2>Update:</h2> <p>As you are using code from <a href="http://www.joe-stevens.com/2009/08/03/generate-a-csv-from-a-generic-list-of-objects-using-reflection-and-extension-methods/" rel="noreferrer">http://www.joe-stevens.com/2009/08/03/generate-a-csv-from-a-generic-list-of-objects-using-reflection-and-extension-methods/</a></p> <p>You need to make the following change to his code:</p> <pre><code>// Make it a simple extension method for a list of object public static string GetCSV(this List&lt;object&gt; list) { StringBuilder sb = new StringBuilder(); //Get the properties from the first object in the list for the headers PropertyInfo[] propInfos = list.First().GetType().GetProperties(); </code></pre> <p>If you want to support an empty list, add second parameter (e.g. <code>Type type</code>) which is the type of object <em>you expected</em> and use that instead of list.First().GetType().</p> <p><em>note: I don't see anywhere else in his code where T is referenced, but if I missed it the compiler will find it for you :)</em></p> <h2>Update (complete &amp; simplified CSV generator):</h2> <pre><code>public static IEnumerable&lt;string&gt; ToCsv(string separator, IEnumerable&lt;object&gt; objectlist) { if (objectlist.Any()) { Type type = objectlist.First().GetType(); FieldInfo[] fields = type.GetFields(); yield return String.Join(separator, fields.Select(f =&gt; f.Name).ToArray()); foreach (var o in objectlist) { yield return string.Join(separator, fields.Select(f=&gt;(f.GetValue(o) ?? "").ToString()).ToArray()); } } } </code></pre> <p>This has the benefit of a low memory overhead as it yields results as they occur, rather than create a massive string. You can use it like:</p> <pre><code>foreach (var line in ToCsv(",", objects)) { Console.WriteLine(line); } </code></pre> <p><em>I prefer the generic solution in practice so have placed that first.</em></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