I am getting the result from LINQ query as var of type IEnumerable<T>
I want a CSV file to be created from the result from the LINQ
I am getting the result from the following query
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()
};
Check this
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);
}
}
Full code at : Scott Hanselman's ComputerZen Blog - From Linq To CSV
IEnumerable<string> lines = r.Select(x => String.Format("{0},{1}", r.Name, r.Count));
System.IO.File.WriteAllLines(path, lines);
will produce:
name1,count1
name2,count2
...
This is screaming out for Linq2CSV:
http://www.codeproject.com/KB/linq/LINQtoCSV.aspx
which is also available on nuget:
http://nuget.org/List/Packages/LinqToCsv
Excellent library, really recommend.
its not clear what you realy want, but this can be a solution public void Read() {
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 NameCount()
{
Name = ResultTable.Key,
Count = ResultTable.Count()
}.ToString();
//Write all r to a File
}
public class NameCount
{
public string Name { get; set; }
public int Count { get; set; }
public string ToString()
{
return string.Format("{0},{1}\r\n", Name, Count);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With