[Solved] Concatenate the properties of a List and write to file in C#


OK. Let’s generalize the problem (see comments for the question): let us join all the properties which are:

  1. public and not static.
  2. Readable and Writable.
  3. Not indexers (what should we do with this[int, int] property?).
  4. Of specified types (e.g. string, int, decimal, double) only (how can we save, a property of, say, IComparer<int> type?).

We can obtain such properties with a help of Reflection and Linq:

  using System.Linq;
  using System.Reflection;

  ...

  HashSet<Type> allowedTypes = new HashSet<Type>() {
    typeof(string), typeof(int), typeof(decimal), typeof(double)
  };

  var properties = typeof(Car)
    .GetProperties(BindingFlags.Instance | BindingFlags.Public)
    .Where(prop => prop.CanRead && prop.CanWrite)
    .Where(prop => !prop.GetIndexParameters().Any())
    .Where(prop => allowedTypes.Contains(prop.PropertyType))
 // .Where(prop => ...) // Add here more coditions if required
    .ToArray();

Now, having these properties we can save values into a file:

  using System.IO;
  using System.Linq;

  ...

  File.WriteAllLines(@"D:\WriteLines.txt", cars
    .Select(car => string.Join(",", properties
       .Select(property => property.GetValue(car)))));

Finally, you can combine these parts into a single routine:

  private static void SaveToFile<T>(IEnumerable<T> source, string fileName) {
    HashSet<Type> allowedTypes = new HashSet<Type>() {
      typeof(string), typeof(int), typeof(decimal), typeof(double)
    };

    var properties = typeof(T)
      .GetProperties(BindingFlags.Instance | BindingFlags.Public)
      .Where(prop => prop.CanRead && prop.CanWrite)
      .Where(prop => !prop.GetIndexParameters().Any())
      .Where(prop => allowedTypes.Contains(prop.PropertyType))
   // .Where(prop => ...) // Add here more coditions if required
      .ToArray();

    File.WriteAllLines(fileName, source
      .Select(item => string.Join(",", properties
        .Select(property => property.GetValue(item))))); 
  } 

Then use it:

  List<Car> cars = new List<Car>();

  ... 

  SaveToFile(Cars, @"D:\WriteLines.txt");

solved Concatenate the properties of a List and write to file in C#