从对象列表中创建一个逗号分隔的字符串

时间:2019-03-15 12:22:02

标签: c# string

我有这些对象的列表

public class OsloProverModel
{
    public string PersonalNumber { get; set; }
    public string SchoolCode { get; set; }
    public string Email { get; set; }
}

我正在尝试使用这些记录制作一个逗号分隔文件。例如,像这样的东西

PN1,SC1,E1
PN2,SC2,E2
....

我正试图遍历和掩饰。 Linq 中有什么方法可以做到吗?

2 个答案:

答案 0 :(得分:5)

覆盖ToString()

public class OsloProverModel
{
    public string PersonalNumber { get; set; }
    public string SchoolCode { get; set; }
    public string Email { get; set; }

    public override string ToString()
    {
        return string.Join(",", new[] { PersonalNumber, SchoolCode, Email });
    }
}

所以你可以

OsloProverModel opmItem = new OsloProverModel()
{
    PersonalNumber = "PN1",
    SchoolCode = "SC1",
    Email = "E1"
};
string result = opmItem.ToString(); //"PN1,SC1,E1"

https://dotnetfiddle.net/7l1G2S


,或者在List<OsloProverModel>和文件的情况下:

List<OsloProverModel> opvItems = GetValues();
System.IO.File.WriteAllLines(@"c:\myfile.csv", opvItems.Select(x => x.ToString()));

答案 1 :(得分:5)

一般情况下,在创建CSV时,如果字符串包含引号",逗号,或换行,则应添加引号; 让我们为其实现一个本地函数:

  Func<string, string> quote = (source) =>
    string.IsNullOrEmpty(source) ? 
        "" 
      : (source.Any(c => c == ',' || c == '"' || c < ' ')) ? 
        $"\"{string.Concat(source.Select(c => c == '"' ? "\"\"" : c.ToString()))}\"" 
      : source;

然后收集了OsloProverModel(例如列表)

  List<OsloProverModel> data = ...

最后,我们可以添加一个简单的 Linq

  File.WriteAllLines(@"c:\MyFile.csv", data
    .Select(item => string.Join(",", 
       quote(item.PersonalNumber), 
       quote(item.SchoolCode),
       quote(item.Email))));