Created
April 5, 2012 11:56
-
-
Save rally25rs/2310325 to your computer and use it in GitHub Desktop.
Anything to CSV
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Linq.Expressions; | |
using System.Text; | |
namespace AnythingToCsv | |
{ | |
public static class EnumerableExtensions | |
{ | |
public static StringBuilder ToCsv<T>(this IEnumerable<T> data, params Expression<Func<T, object>>[] columns) | |
{ | |
var columnFuncs = columns.Select(x => x.Compile()).ToList(); | |
var sb = new StringBuilder(); | |
sb.AppendLine(GetColumnNames(columns)); | |
foreach (var row in data) | |
sb.AppendLine(string.Join(",", columnFuncs.Select(func => func(row).ToString()))); | |
return sb; | |
} | |
private static string GetColumnNames<T>(IEnumerable<Expression<Func<T, object>>> columns) | |
{ | |
return string.Join(",", columns.Select(x => GetColumnName(x.Body))); | |
} | |
private static string GetColumnName(Expression expression) | |
{ | |
if (expression is UnaryExpression) | |
{ | |
var operand = ((UnaryExpression)expression).Operand; | |
if (operand is MemberExpression) | |
return ((MemberExpression)operand).Member.Name; | |
if (operand is MethodCallExpression) | |
return ((MethodCallExpression)operand).Method.Name; | |
} | |
if (expression is MemberExpression) | |
{ | |
return ((MemberExpression)expression).Member.Name; | |
} | |
return string.Empty; | |
} | |
} | |
} | |
using System.Collections.Generic; | |
using AnythingToCsv.Tests.DataStructures; | |
using Microsoft.VisualStudio.TestTools.UnitTesting; | |
namespace AnythingToCsv.Tests | |
{ | |
[TestClass] | |
public class EnumerableToCsvTests | |
{ | |
[TestMethod] | |
public void ToCsv_BuildsExpectedOutput() | |
{ | |
var input = new List<SampleData> | |
{ | |
new SampleData | |
{ | |
IntProp = 1, | |
StringProp = "One" | |
}, | |
new SampleData | |
{ | |
IntProp = 2, | |
StringProp = "Two" | |
} | |
}; | |
var result = input.ToCsv(x => x.IntProp, x => x.StringProp); | |
const string expected = @"IntProp,StringProp | |
1,One | |
2,Two | |
"; | |
Assert.AreEqual(expected, result.ToString()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment