Search code examples
c#.netlinqcsv

IEnumerable<T> to a CSV file


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()
        };

Solution

  • 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