Reputation: 3252
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++;
}
Upvotes: 78
Views: 106374
Reputation: 303
When I work with some database queries, there are some occasions that we need to create part of the string query like this.
So this is my one line approach for this using Split and Join.
String newList = "'" + String.Join("','", list.Split(',')) + "'";
Upvotes: 0
Reputation: 1018
Based off Jon Skeet's example, but modernized for .NET 4+:
// [ "foo", "bar" ] => "\"foo\"", "\"bar\""
string.Join(", ", strList.Select(x => $"\"{x}\""));
Upvotes: 9
Reputation: 1879
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;
}
Upvotes: 0
Reputation: 1571
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 !!!!!!
Upvotes: 0
Reputation: 1500595
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}'"));
Upvotes: 30
Reputation: 31
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.
Upvotes: 0
Reputation: 4368
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());
Upvotes: 123
Reputation: 19392
My Requirements:
Terminate with carriage-return and line-feed.
string.Join(",", lCol.Select(s => s == null ? null : ("\"" + s.Replace("\"", "\"\"") + "\""))) + "\r\n";
Upvotes: 1
Reputation: 680
If you are using JSON, following function would help
var string[] keys = list.Split(',');
console.log(JSON.stringify(keys));
Upvotes: 1
Reputation: 817
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 + "'"));
Upvotes: 35
Reputation: 8005
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.
Upvotes: 0
Reputation: 48265
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);
Upvotes: 0
Reputation: 155935
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,"'");
Upvotes: 0
Reputation: 2821
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);
Upvotes: 1
Reputation: 4132
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) + "'";
Upvotes: 4
Reputation: 41142
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.
Upvotes: 3
Reputation: 19627
string[] splitList = list.Split(',');
string newList = "'" + string.Join("','", splitList) + "'";
Upvotes: 19