DBContext で最新の Entity Framework を使用しています。コンマ区切りの値に変換したい結果セットがあります。VB DataTable to CSV extractの DataTables で同様のことを行いました。QuoteName メソッドが機能しています。また、foreach を使用して動作する GetCSV メソッドの派生物も取得しました。問題は、DataTable の同等のコードよりもかなり遅いことです。だから、誰かがいくつかの提案をしてくれることを願っています。
public static string GetCSV(this IQueryable entity)
{
if (entity == null)
{
throw new ArgumentNullException("entity");
}
Type T = entity.ElementType;
var props = T.GetProperties(BindingFlags.Public | BindingFlags.Instance);
string s = string.Empty;
int iCols = props.Count();
try
{
s += string.Join(",", (from int ii in Enumerable.Range(0, iCols)
select props[ii].Name.QuoteName("[]")).ToArray());
s += Environment.NewLine;
foreach (var dr in entity)
{
s += string.Join(",", (from int ii in Enumerable.Range(0, iCols)
select
props[ii].GetValue(dr)
.ToString()
.QuoteName("\"\"", ",")).ToArray());
s += Environment.NewLine;
}
s = s.TrimEnd(new char[] { (char)0x0A, (char)0x0D });
}
catch (Exception)
{
throw;
}
return s;
}