Tuesday, February 15, 2011

How to convert Generic list into CSV format?

How to convert Generic list into CSV format?
        public static string ListToCSV<T>(List<T> list)
        {
            string output = null;

            foreach (System.Reflection.PropertyInfo info in typeof(T).GetProperties())
            {
                output += ((output==null)?"": ",")+ info.Name;
            }
            output += "\r\n";
            foreach (T t in list)
            {
                string oneline = null;
                foreach (System.Reflection.PropertyInfo info in typeof(T).GetProperties())
                {
                    oneline +=  ((info.GetValue(t, null)==null)?"": info.GetValue(t, null)) +   ",";
                }
                output += oneline + "\r\n";
            }
            return output;
        }

No comments:

Post a Comment