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
Related
I have the below code:
List<string> queryEventIDList=new List<string>();//added new list<string>
foreach (ListItem lstAssign in lstEvent.Items)
{
if (lstAssign.Selected == true)
{
queryEventIDList.Add(lstAssign.Value);
logfield = logfield + "," + lstEvent.SelectedItem.Text;
}
}
string queryEventIDs = string.Join(",", queryEventIDList.ToArray());
From queryEventIDs, I am getting the selected values. I have a below mentioned query line in where condition. Suppose I am selecting A and B,it gives me the result of only A.
" (('" + queryEventIDs + "'='') OR (inq1.event_id in('" + queryEventIDs + "'))) AND " + //queryeventids(A,B)//skips result of B
So I slightly modified that line. I removed single quotes('') from it.
" (('" + queryEventIDs + "'='') OR (inq1.event_id in(" + queryEventIDs + "))) AND " + //Queryeventids(A,B)//gives both result
So this gave me the both selected results of A and B. This is strange. What is the difference for inq1.event_id in('" + queryEventIDs + "' with and without single quotes?
I am a beginner in C#.
Adding Replace solved my issue
" (('" + queryEventIDs + "'='') OR (inq1.event_id in('" + queryEventIDs.Replace(",", "','") + "'))) AND " +
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, ")");
First of all, I'd like to point out that the desired result is a char, not its position index (int).
I'm trying to give my users an option of choosing their desired date format and as such, I've created 2 comboBoxes: comboBox_DateFormatDivider where user chooses between dot, dash and a slash; and comboBox_DateFormat where user chooses date format. comboBox_DateFormat contains a List<string> as follows:
_dateFormatsList = new List<string>()
{
"d-M-yy (" + DateTime.Now.ToString("d-M-yy") + ")",
"dd-M-yy (" + DateTime.Now.ToString("dd-M-yy") + ")",
"d-MM-yy (" + DateTime.Now.ToString("d-MM-yy") + ")",
"dd-MM-yy (" + DateTime.Now.ToString("dd-MM-yy") + ")",
"d-M-yyyy (" + DateTime.Now.ToString("d-M-yyyy") + ")",
"dd-M-yyyy (" + DateTime.Now.ToString("dd-M-yyyy") + ")",
"d-MM-yyyy (" + DateTime.Now.ToString("d-MM-yyyy") + ")",
"dd-MM-yyyy (" + DateTime.Now.ToString("dd-MM-yyyy") + ")",
"yy-M-d (" + DateTime.Now.ToString("yy-M-d") + ")",
"yy-M-dd (" + DateTime.Now.ToString("yy-M-dd") + ")",
"yy-MM-d (" + DateTime.Now.ToString("yy-MM-d") + ")",
"yy-MM-dd (" + DateTime.Now.ToString("yy-MM-dd") + ")",
"yyyy-M-d (" + DateTime.Now.ToString("yyyy-M-d") + ")",
"yyyy-M-dd (" + DateTime.Now.ToString("yyyy-M-dd") + ")",
"yyyy-MM-d (" + DateTime.Now.ToString("yyyy-MM-d") + ")",
"yyyy-MM-dd (" + DateTime.Now.ToString("yyyy-MM-dd") + ")"
};
comboBox_DateFormat.DataSource = _dateFormatsList;
When user chooses different divider, it has to be reflected in the other comboBox, as such DateFormat is dependent on DateFormatDivider, so its contents have to be changed at runtime. And here's the code (and the question) for that:
private void comboBox_DateFormatDivider_SelectedIndexChanged(object sender, EventArgs e)
{
for (int i = 0; i < _dateFormatsList.Count; i++)
{
_dateFormatsList[i] = _dateFormatsList[i].Replace(_dateFormatsList[i].???.ToString(), comboBox_DateFormatDivider.SelectedText);
}
}
Chosen date format is later saved to database, so I guess I could also add another field where divider would be stored, but I'd prefer not to. As you can see, the code above contains ??? in it. So, the question is: how do I replace these question marks with code that will find me the divider it contains?
During those rare cases where you absolutely must do string searching, you can just do the following:
string[] separators = new string[] { "-", ".", "/" };
void DetectCurrentSeparator(string dbDateFormat)
{
for (int i = 0; i < separators.Length; i++)
{
if (dbDateFormat.IndexOf(separators[i]) >= 0)
{
// Assuming the above array corresponds with the order of the divider combobox
combobox_DateFormatDivider.SelectedIndex = i;
break;
}
}
}
Now this having been said, this method should only need to ever be used once during the life of your program - when the date format is first retrieved from the database. For the rest of the time, there is no reason to use any string searching at all for this. You already have the desired divider from your combo box, so instead of trying to figure out what the existing divider is, use a common temporary character and just replace that.
Initialize like so:
DateTime now = DateTime.Now;
_dateFormatsMasterList = new List<string>()
{
"d#M#yy (" + now.ToString("d#M#yy") + ")",
"dd#M#yy (" + now.ToString("dd#M#yy") + ")",
"d#MM#yy (" + now.ToString("d#MM#yy") + ")",
"dd#MM#yy (" + now.ToString("dd#MM#yy") + ")",
"d#M#yyyy (" + now.ToString("d#M#yyyy") + ")",
"dd#M#yyyy (" + now.ToString("dd#M#yyyy") + ")",
"d#MM#yyyy (" + now.ToString("d#MM#yyyy") + ")",
"dd#MM#yyyy (" + now.ToString("dd#MM#yyyy") + ")",
"yy#M#d (" + now.ToString("yy#M#d") + ")",
"yy#M#dd (" + now.ToString("yy#M#dd") + ")",
"yy#MM#d (" + now.ToString("yy#MM#d") + ")",
"yy#MM#dd (" + now.ToString("yy#MM#dd") + ")",
"yyyy#M#d (" + now.ToString("yyyy#M#d") + ")",
"yyyy#M#dd (" + now.ToString("yyyy#M#dd") + ")",
"yyyy#MM#d (" + now.ToString("yyyy#MM#d") + ")",
"yyyy#MM#dd (" + now.ToString("yyyy#MM#dd") + ")"
};
_dateFormatsList = new List<string>(_dateFormatsMasterList);
comboBox_DateFormat.DataSource = _dateFormatsList;
And your SelectionChanged event like so:
private void comboBox_DateFormatDivider_SelectedIndexChanged(object sender, EventArgs e)
{
for (int i = 0; i < _dateFormatsList.Count; i++)
{
_dateFormatsList[i] = _dateFormatsMasterList[i].Replace("#", comboBox_DateFormatDivider.SelectedText);
}
}
Assuming that number of dividers in the Date format are finite, I will do the following:
List<string> dividers = new List<string>{".","/","-"}
private void comboBox_DateFormatDivider_SelectedIndexChanged(object sender, EventArgs e)
{
string currentSeparator = string.Empty;
foreach(var s in dividers)
{
string pattern = #".*(?:\" + s + ").*";
if(Regex.IsMatch(_dateFormatsList[0],pattern))
{
currentSeparator = s;
break;
}
}
for (int i = 0; i < _dateFormatsList.Count; i++)
{
_dateFormatsList[i] = _dateFormatsList[i].Replace(currentSeparator, comboBox_DateFormatDivider.SelectedText);
}
}
Edit 1:
Explanation about regular expression:
Following are details:
".*(?:\.).*",
.* means anything which means 0 or more occurrence, of any character,
?: refers to pattern search matching starts and it expects the character being passed (here "."), (which is escaped, to avoid special treatment of special characters like ., *, ? etc) to be searched in all the data an it will return true on first occurrence or else false.
Edit 2:
To provide an example of the potential of Regular expressions, in the _dateFormatsList, you have multiple date formats, but all the solutions, just pick one value to figure out operator, what about the other values, what if there's data corruption and more than one separators exist, following code will take care of lot of such issues and can further be made strict by changing the pattern:
string pattern = #"^(?!\.\/)[\d]{1,4}[\-][\d]{1,2}[\-][\d]{1,4}$";
It represent all the date formats which contains separator - but not . or /, also there's a digit (\d) repetition, before a separator -, this pattern needs to be applied using Linq All operator as follows:
bool result = _dateFormatsList.All(data => Regex.IsMatch(data,pattern));
This is just to depict, the power of Regular expressions, which no other solution can help achieve, I think most people find Regex complex due to lack of understanding regarding pattern creation
first of all, i'd like to go with Abion47's advice to use a variable to store date and use it in the list.
and then you can do this
char x = _dateFormatsList[0][1];
for (int i = 0; i < _dateFormatsList.Count; i++)
{
_dateFormatsList[i] = _dateFormatsList[i].Replace(x, comboBox_DateFormatDivider.SelectedItem.ToString()[0]);
}
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()) + "]";
I am using Silverlight4 and Telerik Reporting Q3 2011. I am trying to Generate Reports of all Outlets.
I used Table to display its fields. And I want to Display Full Address in same cell.
How could I?
I Used following Experession to display Full Address in same cell.
= Fields.AddressLine1
+ ", " + Fields.AddressLine2
+ ", " + Fields.Suburb
+ ", " + Fields.City
+ ", " + Fields.State
+ ", " + Fields.Country
I want do display this in same cell but want output like below..
=====================
Address
=====================
15A,
xxxx xxxRoad,
xxxxxx,
xxxxxxxx
====================
But I m getting this
=====================
Address
=====================
15A, xxxx xxxRoad, xxxxxx, xxxxxxxx
=====================
How do I get Output Which I want?
Use Environment.NewLine for getting into new line, see below
=Fields.AddressLine1 + ", "
+ Environment.NewLine + Fields.AddressLine2 + ", "
+ Environment.NewLine + Fields.Suburb + ", "
+ Environment.NewLine + Fields.City + ", "
+ Environment.NewLine + Fields.State + ", "
+ Environment.NewLine + Fields.Country;
EDIT
Refer to the link how to insert a newline in Textblock in silverlight
Have you tried using \n or \r\n in your strings wherever you want to do line breaks?
Yes Got it.....
I made the Function NewLineFeeds() in this function I used Replace() Method to replace the specific string to newLine(\n) .
public static string NewLineFeeds(string text)
{
string result = text.Replace(", ", "\n");
result = result.Replace(", ", "\n");
result = result.Replace(", ", "\n");
return result;
}
and my Expression is
=NewLineFeeds(Fields.AddressLine1
+ ", " + Fields.AddressLine2
+ ", " + Fields.Suburb
+ ", " + Fields.City
+ ", " + Fields.State
+ ", " + Fields.Country)
This call the Function NewLineFeeds() and replace ", " to \n (new Line).
Add this will work Fine..
Use complete name System.Environment.NewLine and it will work.
I just confirmed it in my report.