Skip to content

Instantly share code, notes, and snippets.

@jmarnold
Forked from msbukkuri/gist:1252697
Created September 30, 2011 05:05
Show Gist options
  • Save jmarnold/1252725 to your computer and use it in GitHub Desktop.
Save jmarnold/1252725 to your computer and use it in GitHub Desktop.
CsvPrinter
class Program
{
static void Main(string[] args)
{
var values = new List<Sample>();
for (var i = 0; i < 10; i++)
{
values.Add(new Sample
{
Prop1 = Guid.NewGuid().ToString(),
Prop2 = Guid.NewGuid().ToString()
});
}
Print(typeof(Sample).GetProperties(BindingFlags.Instance | BindingFlags.Public), values);
Console.ReadLine();
}
public class Sample
{
public string Prop1 { get; set; }
public string Prop2 { get; set; }
}
public static void Print(IEnumerable<PropertyInfo> properties, IEnumerable<object> instances)
{
var output = new StringBuilder();
var cachedProps = properties.ToArray(); // need indexing here
instances
.Each(x =>
{
var headersWritten = output.Length != 0;
if (!headersWritten)
{
for (var i = 0; i < cachedProps.Length; i++)
{
output.Append(cachedProps[i].Name);
if(i != (cachedProps.Length - 1))
{
output.Append(", ");
}
}
output.AppendLine();
}
for(var i = 0; i < cachedProps.Length; i++)
{
output.Append(cachedProps[i].GetValue(x, null));
if (i != (cachedProps.Length - 1))
{
output.Append(", ");
}
}
output.AppendLine();
});
Console.WriteLine(output.ToString());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment