CSV string handling

后端 未结 13 846
北荒
北荒 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 16:56

    Don't forget our old friend "for". It's not as nice-looking as foreach but it has the advantage of being able to start at the second element.

    public string ReturnAsCSV(ContactList contactList)
    {
        if (contactList == null || contactList.Count == 0)
            return string.Empty;
    
        StringBuilder sb = new StringBuilder(contactList[0].Name);
    
        for (int i = 1; i < contactList.Count; i++)
        {
            sb.Append(",");
            sb.Append(contactList[i].Name);
        }
    
        return sb.ToString();
    }
    

    You could also wrap the second Append in an "if" that tests whether the Name property contains a double-quote or a comma, and if so, escape them appropriately.

提交回复
热议问题