从对象列表中创建逗号分隔列表 [英] Create comma separated list from list of objects
问题描述
我有对象的列表类型Person。这个类有许多属性,我需要他们所有的逗号分隔的列表,所以我可以使用它以后的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.
我已经管理这个与foreach和添加每个属性,用逗号手动分隔它等。
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
这当然不行:
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.
推荐答案
如果可能,我会避免反射。
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.
这篇关于从对象列表中创建逗号分隔列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!