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

后端 未结 16 2006
被撕碎了的回忆
被撕碎了的回忆 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 09:12

    string[] bits = list.Split(','); // Param arrays are your friend
    for (int i=0; i < bits.Length; i++)
    {
        bits[i] = "'" + bits[i] + "'";
    }
    return string.Join(",", bits);
    

    Or you could use LINQ, particularly with a version of String.Join which supports IEnumerable...

    return list.Split(',').Select(x => "'" + x + "'").JoinStrings(",");
    

    There's an implementation of JoinStrings elsewhere on SO... I'll have a look for it.

    EDIT: Well, there isn't quite the JoinStrings I was thinking of, so here it is:

    public static string JoinStrings(this IEnumerable source, 
                                        string separator)
    {
        StringBuilder builder = new StringBuilder();
        bool first = true;
        foreach (T element in source)
        {
            if (first)
            {
                first = false;
            }
            else
            {
                builder.Append(separator);
            }
            builder.Append(element);
        }
        return builder.ToString();
    }
    

    These days string.Join has a generic overload instead though, so you could just use:

    return string.Join(",", list.Split(',').Select(x => $"'{x}'"));
    

提交回复
热议问题