0

I have the following stored in a string.

var _status = "Unknown,Enabled,DisabledAccount,Enabled,Password Does Not Expire,Disabled,Password Does Not Expire,Enabled, Password Does Not Expire"

Desired string so that I can use it in MySQL IN Statement.

var stat = "'Unknown','Enabled','Disabled Account','Enabled, Password Does Not Expire','Disabled, Password Does Not Expire','Enabled, Password Does Not Expire'"

My Code:

string stat = "";
string[] devices = _status.Split(',');
foreach (var d in devices)
{
    stat += "'" + d + "',";
}

stat = stat.TrimEnd(',');

Output

var stat = "'Unknown','Enabled','Disabled Account','Enabled',' Password Does Not Expire','Disabled',' Password Does Not Expire','Enabled',' Password Does Not Expire '"

Thanks

maccettura
  • 10,514
  • 3
  • 28
  • 35
yodellingbutters
  • 285
  • 6
  • 20
  • 4
    What is the problem? Looks like you got your desired output – maccettura Oct 18 '19 at 16:09
  • 1
    `Regex.Split(_status, "(?<!^),(?!\s)")` – Mathias R. Jessen Oct 18 '19 at 16:12
  • 4
    How would you know that some commas are there as separators and some are part of a sentence. Use another separator (or use a completely different format). – Jimi Oct 18 '19 at 16:12
  • 1
    How do you determine that `Enabled,Password Does Not Expire` must not be split on the comma? – Code-Apprentice Oct 18 '19 at 16:13
  • 1
    This will be crazy-vulnerable to sql injection issues. – Joel Coehoorn Oct 18 '19 at 16:13
  • Are you asking about `string.Join` ? I'm assuming you mean you want to generate a comma separated string. But look into this: https://learn.microsoft.com/en-us/dotnet/api/system.string.join?view=netframework-4.8 (Again, I'm making an assumption because it's not very clear what you're asking for.) – Dortimer Oct 18 '19 at 16:13
  • Instead of storing it in a format you *don't* want... how about skip the transform and just store it the proper way to begin with? – Sam Axe Oct 18 '19 at 16:14
  • Zooming in on your sentence: "... so that I can use it in MySQL IN Statement." It seems the main thing you're trying to solve is how to pass an array of parameters to a sql statement. See the duplicate linked and its answer. – Matt Johnson-Pint Oct 18 '19 at 16:19
  • @Mathias R. Jessen Thanks for the Regex. Worked. Can you put it as an answer so that I can mark it. There was a typo in the Regex though - The corrected RegEx is `Regex.Split(_status, "(?<!^),(?!\\s)")` with two \ – yodellingbutters Oct 18 '19 at 16:47
  • @yodellingbutters Can't post an answer on a closed question, but happy to hear you figured it out :) – Mathias R. Jessen Oct 19 '19 at 13:33

0 Answers0