Converting String List to Single Quoted List in C# .NET - c#

I have list of strings. I want to convert each element of it to single quoted string (i.e "ABC" --> 'ABC'), How to do this in .net.
Thanks,
Omkar

Linq can help here.
var newList = oldList.Select(c => c.Replace("\"", "'"));

This is already well answered. However, I have the hunch that you are taking a list of strings in C#, then trying to build an SQL expression for use in IN statements, e.g.:
SELECT * FROM table WHERE name IN ('John','Mary','Peter')
In that case, you'd need to join the strings together, as well as protect from code injection attacks by doubling any single-quote characters.
StringBuilder sb = new StringBuilder();
foreach (string entry in list) {
if (sb.Length > 0) sb.Append(",");
sb.Append("\'" + entry.Replace("'","''") + "\'");
}
string expr = sb.ToString();
You'd also need to handle the special case when the list is empty because IN () is not a valid syntax for SQL.
If this is not what you want, just ignore me. :-)

I assume you have regular strings s to 's' (quoted string) and you wanted a List<> to be converted.
List<string> stringList = new List<string>();
//Fill the list with strings here.
var query = from str in stringList
select string.Format("\'{0}\'", str);
List<string> quotedList = query.ToList<string>();

If you want to replace all double with single quotes, simply do this:
myString = myString.Replace( "\"", "'" );
However, note that ' is not a valid string delimiter in C#, so you can't have the string 'ABC', but you can have the string "'ABC'" that contains the text 'ABC'
EDIT
When looking at Geoff's answer, I saw that you wanted a list. In that case, his answer is almost correct- Try this variant instead:
var convertedList = myStringList.Select(s => s = s.Replace("\"", "'").ToList();

Related

Tokenizing a expression string in C#

I have a calculation formula string of the form
string formula = w_tb + Min(d_3,a_x) * Pow(x,2)
In the above example w_tb, d_3, a_x, x are variables. I am able to find the list of variables in the formula by splitting the strings using the operands as the delimiter.
But in order to assign the values to the variables (value from the database), my first approach was to replace the variable name with the value of the variable from the database. But that would result in replacing even a substring of the expression string with the value. Eg : If the variable x is replaced with the value 1,2 in the expression string a_x will be replaced to a_1,2 which is not the required result.
I have the list of variables and and the complete list of delimiters(operators).
What I am trying to achieve?
I am trying to get the following list from the expression string
List<string>() {"w_tb","+","Min","(","d_3",",","a_x",")","*","Pow","(","x",",","2",")"}
Is there a way I could achieve the task.
I have already tried the solution mentioned in this answer. But the tokenizer I am having is a string.
What you are trying to do is called Parsing, frequently used by compilers.
You can define a simple grammar for your expression and let a parser-generator generate the parser code for you. It allows you to define syntax errors and gives the full token list like the one you want. A very good example in Antlr. Have a look http://www.antlr.org/
So i could find an approach to achieve my task. I have a list of all available operators and a list of all available operands. The list of operands can be obtained by splitting the formula string based on the operator string.
var Operatorlist = new string[] { "Min", "Max", "Abs", "Pow", "+", "-", "*", "/", "(", ")", "²", "³", "Length", " ", "\r", "\n", ",", "[", "]", "Sqrt", "Cubrt", "^" };
string[] formulaSplit = formula.Split(Operatorlist,StringSplitOption.None);
Now to parse the formula to get a list of operands and operators
string sb="";
var formlist = new list<string>();
foreach(var c in calc.CalculationFormula)
{
sb = sb + c;
if(delimstringlist.Contains(sb))
{
formlist.Add(sb);
sb = "";
}
else if(formulaSplit.Contains(sb))
{
formlist.Add(sb);
sb = "";
}
}
May not be so efficient, but will surely do the task.

Splitting string into multiple strings using LINQ

I am trying to split this string
string s = "sn DC0000002; mac 00:0c; uuid 564d6ae4-979";
I need to get these values from above string "DC0000002" , "00:0c" , "564d6ae4-979"
For this I have tried below query but not able to able to get last two values I mean these two values ("00:0c" , "564d6ae4-979")
Below is the query for splitting
List<string> decryptedList = new List<string>();
decryptedList = decodePP.Split(';').Select(x => x.Split(' ')[1]).ToList();
orgSNo = decryptedList[0]; //Output - DC0000002
orgMacID = decryptedList[1];// output - mac // this is wrong need to get value
orgUUID = decryptedList[2]; //output - uuid // this is also wrong
Would anyone please help on this query how extract values from the above string using LINQ query in a single shot?
Just trim substrings which you get after first split:
decodePP.Split(';').Select(x => x.Trim().Split(' ')[1]).ToList();
You get incorrect results, because first split gives you
[ "sn DC0000002", " mac 00:0c", " uuid 564d6ae4-979" ]
As you can see, items except first one have leading whitespace.
Alternative solution - you can use StringSplitOptions.RemoveEmptyEntries parameter to skip empty substrings
str.Split(';')
.Select(x => x.Split(new char[]{' '}, StringSplitOptions.RemoveEmptyEntries)[1])
.ToList()
Why do you need to use Linq. The string split would seem to do the trick?
string[] keyValuePairs = s.Split(';');
foreach(string pair.Trim() in keyValuePairs)
{
string key = pair.Split(' ')[0].Trim();
string value = pair.Split(' ')[1].Trim();
}
That's only a stab at the code - it may not compile, but you get the idea?
You could use the TrimStart() function in your linq statement like:
decryptedList = decodePP.Split(';').Select(x => x.TrimStart().Split(' ')[1]).ToList();

Add prefix/suffix to each member of an IEnumerable<string> in C#

Is there an easy way to add a prefix or suffix to each member of an IEnumerable? I can't figure out a way besides (Where inputs is IEnumerable):
var sb = new StringBuilder();
foreach (var str in inputs) {
str = sb.Append(prefix).Append(str).ToString();
sb.clear();
}
But this won't let me assign back to the str... And I feel like there should be a better way to do this.
This should work:
var result = inputs
.Select(x => prefix + x)
.ToList();
It simply creates a new string for each input prepending the prefix and then put them into a list.For suffix just change prefix + x to x + suffix.
It worth to mention two wrong things with your code:
Your str variable is should be readonly inside foreach loop and you can't assign to it because strings are immutable and when you're calling sb.Append(prefix).Append(str).ToString(); it creates a new string;
You don't need StringBuilder for this kind of task because it efficient when you do several concatenations to one string. In your case you have several strings each of which you need to concatenate with some variable only once.
Strings are immutable, so you can't just modify them whenever you want. You can return a new list though:
IEnumberable<String> AppendString (IEnumerable<String> src, String append)
{
foreach (String str in src)
yield return str + append;
}

Join strings without repeating delimiter

a friend told me about a function to combine strings with a delimiter without having to worry about whether or not the delimiter is already present in the strings, but i cant remember the function
ex:
var stringArray = new string[]{"windows", "\users", "JohnSmith", "\Documents"};
var tempString = whateverFunction(stringArray, "\")
joins the strings into
tempstring = "windows\users\JohnSmith\Documents"
any help with this would be great, thanks
You might be thinking of Path.Combine, but it doesn't work quite like you describe.
var stringArray = new[] {"windows", "\\users", "JohnSmith", "\\Documents"};
var tempString = Path.Combine(stringArray);
That results in \Documents because it took the last as an absolute path. This method does what you are asking for (trims the joining character from the edges, not throughout).
string WhateverFunction(string[] values, char join)
{
return String.Join(join.ToString(), values.Select(x => x.Trim(join)));
}
var stringArray = new[] {"windows", "\\users", "JohnSmith", "\\Documents"};
var tempString = WhateverFunction(stringArray, '\\');
Results in windows\users\JohnSmith\Documents
I think you're looking for Path.Combine(), though that is specific to paths, and not a general answer to the question.
I would use explicit string arrays, in which case "\users", etc., is invalid with the back-slash - it requires two back-slashes (to escape the slash).
string[] stringArray = new string[]{"windows", "\\users", "JohnSmith", "\\Documents"};
string tempString = String.Join("\\", stringArray).Replace("\\\\","\\");
Console.WriteLine(tempString);
// windows\users\JohnSmith\Documents
Replace() is used to remove the duplication of the slashes.

Regex for Removing All the repetation of a string and assign to an array

I have the following text in a file:
"SHOP_ORDER001","SHOP_ORDER002","SHOP_ORDER003","SHOP_ORDER004","SHOP_ORDER005"
Now I am getting the values by reading the file and assigning to array by spilt:
String orderValue = "";
string[] orderArray;
orderValue = File.ReadAllText(#"C:\File.txt");
orderArray = orderValue.Split(',');
But I am getting the values as :
I need the Values in Array as "ORDER001","ORDER002","ORDER003"
The \" you see is just added by debugger visualizer for strings (because quote is a special characted and need to be escaped to don't get confused), don't worry they're not in your orderArray.
In case you want to remove quotes too so that your array will be:
SHOP_ORDER001
SHOP_ORDER002
...
Just use this (with LINQ):
var orderArray = orderValue.Split(',').Select(x => x.Trim('"'));
By the way String.Split isn't very robust unless you're sure each field will never contain a comma.
EDIT
To answer the point you added in the comments if you need to remove SHOP_ just write this:
var orderArray = orderValue.Split(',')
.Select(x => x.Trim('"').Substring("SHOP_".Length));
use this regex
var res = Regex.Matches(orderValue, #"(?<=""SHOP_)[^""]+?(?="")");
You could use this:
string[] result = Regex.Split(orderValue, "(?:^\"SHOP_)|(?:\",\"SHOP_)|(?:\"$)");
However you will have to skip the first and last items in the resulting array as they will always be empty strings.
Silly question but why don't you just do
.Replace("SHOP_", "");

Categories