Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create comma separated list from list of objects

Tags:

c#

list

csv

I have list of objects type Person. This class has many properties and I need them all in a comma separated list so I can use it later for Csv file.

I've managed this with foreach and adding each property, separating it with commas manual, etc.

const string commaSeparator = ",";
foreach (var item in individualsInformation)
{
    csv.AppendLine(item.ReferenceNumber + commaSeparator + item.FirstName + commaSeparator +
                   item.Surname + commaSeparator + item.MiddleName + commaSeparator +
                   item.Address1 + commaSeparator + item.Address2 + commaSeparator + 
                   item.Address3 + commaSeparator + item.Address4 + commaSeparator + 
                   item.City + commaSeparator + item.PostalCode + commaSeparator +
                   item.Country + commaSeparator + item.DateOfBirth.ToString() + commaSeparator +
                   item.ID + commaSeparator + item.Gender + commaSeparator +
                   item.Component + commaSeparator + item.NationalID + commaSeparator + 
                   item.SubSystemID + commaSeparator + item.System);
}

Then I've realized that there is much efficient way, by using string.Join

This does not work of course:

string joined = string.Join(",", listOfPersons);

And if I go by selecting property like this:

string joined = string.Join(",", listOfPersons(x => x.Id);

I get comma separated list only for that property of course.

Is there some more efficient way for getting each property separated by comma?

like image 723
nemo_87 Avatar asked Apr 04 '16 08:04

nemo_87


2 Answers

I would avoid reflection if possible.

You can achieve it with compile time safety and readable code easily:

IEnumerable<string> personTexts = listOfPersons
    .Select(p => String.Join(",", p.ReferenceNumber, p.FirstName, p.Surname, ...));
string joined = String.Join(Environment.NewLine, personTexts);

You have full control over which property should be used and in which order.

like image 80
Tim Schmelter Avatar answered Sep 18 '22 23:09

Tim Schmelter


Reflection is (sometimes) your friend:

var props = item.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance); // todo: cache & filter not-needed props)

var itemStr = string.Join(", ", 
                     props.Select(p => p.GetValue(item, null)?.ToString())
                          .ToArray());
like image 26
pwas Avatar answered Sep 20 '22 23:09

pwas