我从LINQ查询中得到的结果是IEnumerable<T>
类型的var
我想从LINQ的结果中创建一个CSV文件
我从以下查询中得到结果
var r = from table in myDataTable.AsEnumerable()
orderby table.Field<string>(para1)
group table by new { Name = table[para1], Y = table[para2] }
into ResultTable
select new
{
Name = ResultTable.Key,
Count = ResultTable.Count()
};
最佳答案
检查一下
public static class LinqToCSV
{
public static string ToCsv<T>(this IEnumerable<T> items)
where T : class
{
var csvBuilder = new StringBuilder();
var properties = typeof(T).GetProperties();
foreach (T item in items)
{
string line = string.Join(",",properties.Select(p => p.GetValue(item, null).ToCsvValue()).ToArray());
csvBuilder.AppendLine(line);
}
return csvBuilder.ToString();
}
private static string ToCsvValue<T>(this T item)
{
if(item == null) return "\"\"";
if (item is string)
{
return string.Format("\"{0}\"", item.ToString().Replace("\"", "\\\""));
}
double dummy;
if (double.TryParse(item.ToString(), out dummy))
{
return string.Format("{0}", item);
}
return string.Format("\"{0}\"", item);
}
}
完整代码位于:Scott Hanselman's ComputerZen Blog - From Linq To CSV
关于c# - IEnumerable <T>转换为CSV文件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6199644/