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

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

    Here is a C# 6 solution using String Interpolation.

    string newList = string.Join(",", list.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                           .Select(x => $"'{x}'")
                           .ToList());
    

    Or, if you prefer the C# 5 option with String.Format:

    string newList = string.Join(",", list.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                           .Select(x => String.Format("'{0}'", x))
                           .ToList());
    

    Using the StringSplitOptions will remove any empty values so you won't have any empty quotes, if that's something you're trying to avoid.

提交回复
热议问题