I've got a very simple problem but can't seem to figure it out. I've created a list of strings. But i want to format the list into a string that looks like an array.
So for example this is my list
List<string> testData = new List<string> ();
testData.Add("test 1");
testData.Add("test 2");
I want to then format all the data into a string hopefully to look like this:
['test 1', 'test 2']
Ive tried to use a string.Join but that doesnt get the results I'm looking for.
Ive tried to use a string.Join but that doesn't get the results I'm looking for.
That's true. However, string format can help:
var res = "[" + string.Join(", ", testData.Select(s => $"'{s}'")) + "]";
Prior to C# 6, you would need to use string.Format explicitly:
var res = "[" + string.Join(", ", testData.Select(s => string.Format("'{0}'", s))) + "]";
var result = "[" + String.Join(", ", testData.Select(c => "'" + c + "'")) + "]";
string result = "[" + string.Join(",", testData.Select(i => "'" + i + "'").ToArray()) + "]";
Related
I am selecting values from two DropDownList and my condition is to remove only the last comma from the list (Getting the DropDownList into List). This is an old issue, I know but stuck into a simple one. This is what I've tried so far:
var ddlAll = new List<DropDownList>() //Lists of DropDownList
{
ddl1, //DropDownList 1
ddl2 //DropDownList 2
};
foreach(var item in ddlAll) //Iterating through for loop
{
lblShow.Text += "'" + item.SelectedValue + "'" + ", ".TrimEnd(',', ' '); //Getting the values here and trying to remove the last comma
}
With the above code, I get the following output:
'Hello 2''Hello 4'
But my expected output is as follows:
'Hello 2', 'Hello 4'
Without the TrimEnd(), I get this:
'Hello 2', 'Hello 4',
N.B: There could be more DropDownList values but it should only remove the last comma from them.
You're doing Trim in every iteration. You have to change code to do it only ones, at the end. For example like this:
string text = "";
foreach(var item in ddlAll)
{
text += "'" + item.SelectedValue + "'" + ", ";
}
lblShow.Text = text.TrimEnd(',', ' ');
Also, I would rewrite this:
"'" + item.SelectedValue + "'" + ", ".TrimEnd(',', ' ');
using string.Format into:
string.Format("'{0}',", item.SelectedValue);
or even, if you are using C#6 or later, into this :
$"'{item.SelectedValue}',";
Just use String.Join
String.Join(",", new List<string> { "Hello 2", "Hello 4" })
In your case the second parameter would be
ddlAll.Select(x => x.SelectedValue)
foreach(var item in ddlAll) //Iterating through for loop
{
if(lblShow.Text=='')
{
lblShow.Text = "'" + item.SelectedValue + "'";
}
else
{
lblShow.Text += ", " +"'" + item.SelectedValue + "'";
}
}
I have below string
string str= "Insert into " + tname + "(id, t, v) values(" + lc+ ", " + mc+ ", " + rc+");" + Environment.NewLine;
and I'm write it to file:
File.AppendAllText(fileName, str);
It's working.
I also tried to use string.Join:
string str = string.Join("Insert into " + tname+ "(id, t, v) values(" + lc+ ", " + mc+ ", " + rc+ ");", Environment.NewLine);
File.AppendAllText(fileName, str);
but the file always is empty. What is wrong?
i think what you need is string.Format()
string str = string.Format("Insert into {0}(id, t, v) values({1}, {2}, {3});{4}",tname, lc,mc,rc, Environment.NewLine);
String.Format() documentation
string.Join is to concatenate a String[] of objects using a separator
eg
List<int> l= new List { 1,2,3 };
var s = string.Join(",",l);
s is then "1,2,3"
In your code you are basically passing in a very long separator (your string) and an empty array.
Documentation for string.Join
I am really new to ASP.NET, C#.
Now I am trying to write a little method, what is build me an sql query.
(Later I will use prepared statements, now I am just try to get acquainted with the environment, with the language, etc...)
Here is my method:
public void insert( string table, Dictionary<string, string> dataToInsert ) {
string sql = "INSERT INTO " + table;
if (dataToInsert.Count< 1) {
throw new Exception("No data to insert to table: " + table);
}
List<string> fieldNames = getFieldNames(dataToInsert);
List<string> aposthrofedFieldNames = getApostrophedValues(fieldNames);
List<string> values = getValues(dataToInsert);
List<string> aposthrofedValues = getApostrophedValues(values);
string fieldNamesString = string.Join(", ", aposthrofedFieldNames);
string valuesString = string.Join(", ", aposthrofedValues);
sql += " (" + fieldNamesString + ") VALUES (" + valuesString + ")";
}
The fieldNamesString and valuesString are just concatenated strings like `'userId', 'loginDate', ... so nothing special, just strings.
At this line:
sql += " (" + fieldNamesString + ") VALUES (" + valuesString + ")";
the sql variable has gone. Can not be watchable, no more datatip.
What do I do wrong?
EDIT
Screenshot:
UPDATE
If I am using this, sql will be ok:
sql = string.Concat(sql, " (", fieldNamesString, ") VALUES (", valuesString, ")");
I have a simple question for the LINQ experts.
I want create a single string based in an Array:
return String.Join(",", (from string val
in arrayValues
select new { value = "%" + val.ToString() + "%" })
.Distinct().ToArray());
This code give an error, but I cannot found the way how fix the issue.
Example; I want to send {"1","2","3","4"} and my expected result should be something like that: "%1%,%2%,%3%,%4%"
Any help will be welcome!
It's not clear from your example why you need Distinct but you can do:
return string.Join(",", arrayValues.Distinct().Select(s => "%" + s + "%"));
or
var values = from val in arrayValues.Distinct() select "%" + val + "%";
return string.Join(",", values);
You can just use:
return String.Join(",", arrayValues.Distinct().Select(v => "%" + v + "%"));
If you always will have at least one element, you could also use:
return "%" + string.Join("%,%", arrayValues.Distinct()) + "%";
I am adding mutliple values to single string , all the values should be like in this format '','' but I am getting "'',''" instead.
How can I remove these double qoutes? Here's the code I'm using:
string one = "\'"+ names[0, 0] +"\'"+","+"\'" + names[1, 0]+"\'";
string[] splitted = one.Split('\'');
string ones = "'" + splitted[1] + "'" +","+ "'" + splitted[3] + "'";
You don't have to escape single quote like "\'" instead you can simply use "'", so you code should be:
string one = "'" + names[0, 0] + "'" + "," + "'" + names[1, 0] + "'";
string[] splitted = one.Split('\'');
string ones = "'" + splitted[1] + "'" + "," + "'" + splitted[3] + "'";
Not sure I fully understand, but there are two ways.
Output: ".","."
var s1 = #"""."","".""";
var s2 = "\".\",\".\"";
The best way to encapsualte escape sequences and special characters within a string is the use of webatim character.
e.g.
String escSeq = "C:\\MyDocuments\\Movie";
can also be stored as:
string escSeq = #"C:\MyDocumens\Movie";
The # character you must put before the string starts and outside the "" characters.
I just worked with your code..it works just fine..
Debugger will show: "'val1','val2'"
Actual Value : 'val1','val2'
From the debugger point you will see "'val1','val2'" but actually it happens for every string values. but actually when you prints the value in a page you will see the actual value as 'val1','val2'
EDIT:
For sending those values to javascript what you can do is just set those values in Hidden fields and then fetch those value from that using document.getElementById('hidden_field').