1

I have a class like this

class Car
{
   public string carname{get;set;}
   public int id{get;set};
   public string mdate{get;set;}
}

I have a List of Car and I need to write each of the car's properties as a delimited string into a file

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

Right now am achieving it using loop as below

foreach(car c in cars)
{
    string s=c.carname + "," + c.id + "," + c.mdate;
    f.writeline(s);
}

But if the number of properties are huge its difficult to do the same. So is there is any easy way to achieve the above. Something like linq or any other way..

Also is there is any way of specifying the order of columns in CSV

PonWer
  • 87
  • 1
  • 7
Sandeep Thomas
  • 4,303
  • 14
  • 61
  • 132
  • 1
    `var data = cars.Select(x => string.Format("{0},{1},{2}",x.carname,x.id,x.mdate)).ToList();` – Rahul Jan 08 '19 at 08:28

1 Answers1

0

Using Reflection you can get a list of the property definitions on a class, you can then loop through the properties and get the values. This might give you a way to dynamically generate your list from an extensive list of properties.

Here is another Stack Overflow question that asks the question a different way, it is possible your question here is a duplicate of this original one.

How can you loop over the properties of a class?

SazooCat
  • 150
  • 1
  • 6
  • Doesn't this return a lot of Properties not defined within the class and create a flustercluck of useless information? – MindSwipe Jan 08 '19 at 08:27
  • why reflection needed at all – Rahul Jan 08 '19 at 08:29
  • 1
    @Rahul The original question was concerned with an object having a large number of properties and having to code for each one. Reflection would allow them to generate the list without needing to pre-code for each property. – SazooCat Jan 08 '19 at 08:31