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

C#String

C# Problem Overview


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 list = "Fred,Sam,Mike,Sarah";

How would get each element and add quotes around it and stick it back in a string like this:

string newList = "'Fred','Sam','Mike','Sarah'";

I'm assuming iterating over each one would be a start, but I got stumped after that.

One solution that is ugly:

int number = 0;
string newList = "";
foreach (string item in list.Split(new char[] {','}))
{
    if (number > 0)
    {
        newList = newList + "," + "'" + item + "'";
    }
    else
    {
        newList = "'" + item + "'";
    }
    number++;
}

C# Solutions


Solution 1 - C#

string s = "A,B,C";
string replaced = "'"+s.Replace(",", "','")+"'";

Thanks for the comments, I had missed the external quotes.

Of course.. if the source was an empty string, would you want the extra quotes around it or not ? And what if the input was a bunch of whitespaces... ? I mean, to give a 100% complete solution I'd probably ask for a list of unit tests but I hope my gut instinct answered your core question.

Update: A LINQ-based alternative has also been suggested (with the added benefit of using String.Format and therefore not having to worry about leading/trailing quotes):

string list = "Fred,Sam,Mike,Sarah";
string newList = string.Join(",", list.Split(',').Select(x => string.Format("'{0}'", x)).ToList());

Solution 2 - C#

Following Jon Skeet's example above, this is what worked for me. I already had a List<String> variable called __messages so this is what I did:

string sep = String.Join(", ", __messages.Select(x => "'" + x + "'"));

Solution 3 - C#

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<string>...

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<T>(this IEnumerable<T> 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}'"));

Solution 4 - C#

string[] splitList = list.Split(',');
string newList = "'" + string.Join("','", splitList) + "'";

Solution 5 - C#

Based off Jon Skeet's example, but modernized for .NET 4+:

// [ "foo", "bar" ] => "\"foo\"", "\"bar\""  
string.Join(", ", strList.Select(x => $"\"{x}\""));

Solution 6 - C#

I think the simplest thing would be to Split and then Join.

string nameList = "Fred,Sam,Mike,Sarah";
string[] names = nameList.Split(',');
string quotedNames = "'" + string.Join("','", names) + "'";

Solution 7 - C#

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.

Solution 8 - C#

string list = "Fred,Sam,Mike,Sarah";

string[] splitList = list.Split(',');

for (int i = 0; i < splitList.Length; i++)
    splitList[i] = String.Format("'{0}'", splitList[i]);

string newList = String.Join(",", splitList);

Solution 9 - C#

If you are using JSON, following function would help

var string[] keys = list.Split(',');
console.log(JSON.stringify(keys));

Solution 10 - C#

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";

Solution 11 - C#

The C# implementation of @PhiLho's JavaScript regular expression solution looks something like the following:

Regex regex = new Regex(
    @"\b",
    RegexOptions.ECMAScript
    | RegexOptions.Compiled
    );

string list = "Fred,Sam,Mike,Sarah";
string newList = regex.Replace(list,"'");

Solution 12 - C#

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);

Solution 13 - C#

Are you going to be processing a lot of CSV? If so, you should also consider using a library to do this. Don't reinvent the wheel. Unfortunately I haven't found a library quite as simple as Python's CSV library, but I have seen FileHelpers (free) reviewed at MSDN Magazine and it looks pretty good. There are probably other free libraries out there as well. It all depends on how much processing you will be doing though. Often it grows and grows until you realize you would be better off using a library.

Solution 14 - C#

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.

Solution 15 - C#

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 !!!!!!

Solution 16 - C#

For people who love extension methods like me, here it is:

    public static string MethodA(this string[] array, string seperatedCharecter = "|")
    {
        return array.Any() ? string.Join(seperatedCharecter, array) : string.Empty;
    }

    public static string MethodB(this string[] array, string seperatedChar = "|")
    {
        return array.Any() ? MethodA(array.Select(x => $"'{x}'").ToArray(), seperatedChar) : string.Empty;
    }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBob WintembergView Question on Stackoverflow
Solution 1 - C#FORView Answer on Stackoverflow
Solution 2 - C#vcuankitView Answer on Stackoverflow
Solution 3 - C#Jon SkeetView Answer on Stackoverflow
Solution 4 - C#Tor HaugenView Answer on Stackoverflow
Solution 5 - C#dylanh724View Answer on Stackoverflow
Solution 6 - C#Jacob CarpenterView Answer on Stackoverflow
Solution 7 - C#PhiLhoView Answer on Stackoverflow
Solution 8 - C#RickLView Answer on Stackoverflow
Solution 9 - C#Atish NarlawarView Answer on Stackoverflow
Solution 10 - C#MikeTeeVeeView Answer on Stackoverflow
Solution 11 - C#bdukesView Answer on Stackoverflow
Solution 12 - C#bruno condeView Answer on Stackoverflow
Solution 13 - C#RyanView Answer on Stackoverflow
Solution 14 - C#KenBView Answer on Stackoverflow
Solution 15 - C#Thivan MydeenView Answer on Stackoverflow
Solution 16 - C#Dheeraj PalagiriView Answer on Stackoverflow