This is a cool function to create a csv string from a generic list in C#:

public static string CreateCSVFromGenericList<T>(List<T> list)
            if (list == null || list.Count == 0) return "";

            //get type from 0th member
            Type t = list[0].GetType();
            string newLine = Environment.NewLine;

            var sw = new StringBuilder();

             //make a new instance of the class name we figured out to get its props
            object o = Activator.CreateInstance(t);
            //gets all properties
            PropertyInfo[] props = o.GetType().GetProperties();

            //foreach of the properties in class above, write out properties
            //this is the header row
            sw.AppendLine(string.Join(",", props.Select(d => d.Name).ToArray()));

            //this acts as datarow
            foreach (T item in list)
                //this acts as datacolumn
                var row = string.Join(",", props.Select(d => item.GetType()
                                                                .GetValue(item, null)

            return sw.ToString();
Post comment