【发布时间】:2016-07-23 17:16:48
【问题描述】:
我有 Person 类型的对象列表。这个类有很多属性,我需要它们都放在一个逗号分隔的列表中,这样我以后可以将它用于 Csv 文件。
我已经用 foreach 管理了这个并添加了每个属性,用逗号分隔,等等。
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);
}
然后我意识到通过使用 string.Join 有很多有效的方法
这当然行不通:
string joined = string.Join(",", listOfPersons);
如果我选择这样的属性:
string joined = string.Join(",", listOfPersons(x => x.Id);
当然,我只为该属性获取逗号分隔列表。
有没有更有效的方法让每个属性用逗号分隔?
【问题讨论】:
-
停止尝试重新发明轮子。查看答案here
-
您当前的方法并不全是坏事,也是完全控制一切的唯一方法。