Skip to content

Instantly share code, notes, and snippets.

@miya2000
Last active December 22, 2015 05:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save miya2000/6424939 to your computer and use it in GitHub Desktop.
Save miya2000/6424939 to your computer and use it in GitHub Desktop.
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
namespace UnitTestProject1
{
[TestClass]
public class CsvConvertUsingAnonymousTypeTest
{
public class Hoge
{
public int P1 { get; set; }
public string P2 { get; set; }
}
[TestMethod]
public void CsvConvertUsingAnonymousType()
{
var entities = new[] {
new Hoge(){ P1 = 10, P2 = "Hoge" },
new Hoge(){ P1 = 20, P2 = "Fuga" },
new Hoge(){ P1 = 30, P2 = "Piyo" }
};
var csvWithHeader = entities.ToCsv(n => new { n.P1, n.P2, P3 = n.P1 + n.P2 }, true);
csvWithHeader.Is(
@"P1,P2,P3
10,Hoge,10Hoge
20,Fuga,20Fuga
30,Piyo,30Piyo");
var csvNoHeader = entities.ToCsv(n => new { n.P1, n.P2, P3 = n.P1 + n.P2 }, false);
csvNoHeader.Is(
@"10,Hoge,10Hoge
20,Fuga,20Fuga
30,Piyo,30Piyo");
var Var1 = "local";
var csvSample1 = entities.ToCsv(n => new { n.P1, n.P2, P3 = n.P1 + n.P2, Var1 }, true);
csvSample1.Is(
@"P1,P2,P3,Var1
10,Hoge,10Hoge,local
20,Fuga,20Fuga,local
30,Piyo,30Piyo,local");
}
}
public static class Csv
{
public static string ToCsv<T, TResult>(this IEnumerable<T> items, Expression<Func<T, TResult>> exp, bool withHeader = true)
{
if (!(exp.Body is NewExpression)) throw new ArgumentException("Requires NewExpression.", "exp");
var ctor = (NewExpression)exp.Body;
var header = from _ in " " where withHeader select ctor.Members.Select(n => n.Name).ToArray();
var lambda = Expression.Lambda<Func<T, object[]>>(Expression.NewArrayInit(typeof(object), ctor.Arguments.Select(n => Expression.Convert(n, typeof(object)))), exp.Parameters[0]).Compile();
return string.Join("\r\n", header.Concat(items.Select(lambda)).Select(n => string.Join(",", n.Select(s => EscForCsv(s)))));
}
private static object EscForCsv(object value)
{
//TODO Implement.
return value;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment