In C#: Add Quotes around string in a comma delimited list of strings

后端 未结 16 1787
被撕碎了的回忆
被撕碎了的回忆 2021-01-30 08:18

This probably has a simple answer, but I must not have had enough coffee to figure it out on my own:

If I had a comma delimited string such as:

string li         


        
相关标签:
16条回答
  • 2021-01-30 08:49

    My Requirements:

    1. Separate items using commas.
    2. Wrap all items in list in double-quotes.
    3. Escape existing double-quotes in the string.
    4. Handle null-strings to avoid errors.
    5. Do not bother wrapping null-strings in double-quotes.
    6. Terminate with carriage-return and line-feed.

      string.Join(",", lCol.Select(s => s == null ? null : ("\"" + s.Replace("\"", "\"\"") + "\""))) + "\r\n";

    0 讨论(0)
  • 2021-01-30 08:50

    I can't write C# code, but this simple JavaScript code is probably easy to adapt:

    var s = "Fred,Sam,Mike,Sarah";
    alert(s.replace(/\b/g, "'"));
    

    It just replace bounds (start/end of string, transition from word chars non punctuation) by single quote.

    0 讨论(0)
  • 2021-01-30 08:52

    If you are using JSON, following function would help

    var string[] keys = list.Split(',');
    console.log(JSON.stringify(keys));
    
    0 讨论(0)
  • 2021-01-30 08:53

    I have found a new solution for this problem

    I bind a list by selected items values from the grid using linq, after that added a comma delimited string for each string collections by using String.Join() properties.

    String str1 = String.Empty;
    String str2 = String.Empty;              
    //str1 = String.Join(",", values); if you use this method,result "X,Y,Z"
         str1 =String.Join("'" + "," + "'", values);
    //The result of str1 is "X','Y','Z"
         str2 = str1.Insert(0, "'").Insert(str1.Length+1, "'");
    //The result of str2 is 'X','Y','Z'
    

    I hope this will helpful !!!!!!

    0 讨论(0)
  • 2021-01-30 08:54

    My "less sophisticated" approach ... I suppose it's always good practice to use a StringBuilder because the list can be very large.

    string list = "Fred,Sam,Mike,Sarah";
    StringBuilder sb = new StringBuilder();
    
    string[] listArray = list.Split(new char[] { ',' });
    
    for (int i = 0; i < listArray.Length; i++)
    {
        sb.Append("'").Append(listArray[i]).Append("'");
        if (i != (listArray.Length - 1))
            sb.Append(",");
    }
    string newList = sb.ToString();
    Console.WriteLine(newList);
    
    0 讨论(0)
  • 2021-01-30 08:56
    string[] splitList = list.Split(',');
    string newList = "'" + string.Join("','", splitList) + "'";
    
    0 讨论(0)
提交回复
热议问题