ListExtension.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Reflection;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. public static class ListExtension
  9. {
  10. /// <summary>
  11. /// Save the List data to CSV file
  12. /// </summary>
  13. /// <param name="list">data source</param>
  14. /// <param name="file">file</param>
  15. /// <returns>success flag</returns>
  16. public static string ToCsvFile<T>(this List<T> list, string file)
  17. {
  18. PropertyInfo[] props = GetPropertyInfoArray<T>();
  19. using (var sw = new StreamWriter(file))
  20. {
  21. StringBuilder strColumn = new StringBuilder();
  22. for (int i = 0; i < props.Length; i++)
  23. {
  24. strColumn.Append(props[i].Name);
  25. strColumn.Append(",");
  26. }
  27. strColumn.Remove(strColumn.Length - 1, 1);
  28. sw.WriteLine(strColumn); //write the column name
  29. for (int i = 0; i < list.Count; i++)
  30. {
  31. StringBuilder strValue = new StringBuilder();
  32. int idx = 0;
  33. foreach (var prop in props)
  34. {
  35. var val = prop.GetValue(list[i]);
  36. strValue.Append(val);
  37. if (idx < props.Length-1)
  38. strValue.Append(",");
  39. idx++;
  40. }
  41. sw.WriteLine(strValue); //write the row value
  42. }
  43. }
  44. FileInfo f = new FileInfo(file);
  45. return f.FullName;
  46. }
  47. private static PropertyInfo[] GetPropertyInfoArray<T>()
  48. {
  49. PropertyInfo[] props = null;
  50. Type type = typeof(T);
  51. object obj = Activator.CreateInstance(type);
  52. props = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
  53. return props.Where(p => p.CanRead && !p.GetMethod.IsVirtual && !p.GetMethod.IsAbstract).ToArray();
  54. }
  55. }