CSV string handling

后端 未结 13 842
北荒
北荒 2020-12-28 16:44

Typical way of creating a CSV string (pseudocode):

  1. Create a CSV container object (like a StringBuilder in C#).
  2. Loop through the strings you want to ad
13条回答
  •  [愿得一人]
    2020-12-28 17:15

    You could also make an array of c.Name data and use String.Join method to create your line.

    public string ReturnAsCSV(ContactList contactList)
    {
        List tmpList = new List();
    
        foreach (Contact c in contactList)
        {
            tmpList.Add(c.Name);
        }
    
        return String.Join(",", tmpList.ToArray());
    }
    

    This might not be as performant as the StringBuilder approach, but it definitely looks cleaner.

    Also, you might want to consider using .CurrentCulture.TextInfo.ListSeparator instead of a hard-coded comma -- If your output is going to be imported into other applications, you might have problems with it. ListSeparator may be different across different cultures, and MS Excel at the very least, honors this setting. So:

    return String.Join(
        System.Globalization.CultureInfo.CurrentCulture.TextInfo.ListSeparator,
        tmpList.ToArray());
    

提交回复
热议问题