Wednesday, 23 December 2015

put single quote in string c#

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++;
}

No comments:

Post a Comment