C#: How to add double quotes in variable - c#

i am developing silverlight application. right now, i have an issue to pass string variable to sql statement, together with double quotes. i tried using this way:
string itemList;
string commaString = #"""";
for (int i = 0; i < TestList.Count; i++)
{
itemList += commaString + TestList[i].Code + commaString + " || ";
}
itemList = "x.Code == " + itemList;
itemList = itemList.Removed(itemList.Length - 3);
but the variable passed is like this:
" x.Code == \" 11001-111001 \" || x.Code == \" 11016-111001 \"
"
i want it to be this way:
x.Code == "11001-111001" || x.Code == "11016-111001"
i dont want the back slash. i want to pass this variable to sql select statement. is it possible to do this? can anybody help me? thank you...
***Updated:
my TestList currently have 2 values:
"11001-111001"
"11016-111001"
and then i want to combine these values in itemList to be:
x.Code == "11001-111001" || x.Code == "11016-111001"
since i want to use this in sql statement. when combined, now becomes
" x.Code == \"11001-111001\" || x.Code == \"11016-111001\" "
below is how i want to use the variable. i want to replace the codes with itemList:
private void GetAccountCodes()
{
var r = _svc.AccountCodes.Where(x => x.Code == "11001-111001" || x.Code == "11016-111001").Select(x => x);
_company.AccountCodes.LoadCompleted -= new EventHandler<LoadCompletedEventArgs>(AccountCodes_LoadCompleted);
_company.AccountCodes.LoadCompleted += new EventHandler<LoadCompletedEventArgs>(AccountCodes_LoadCompleted);
_company.AccountCodes.Clear(true);
_company.AccountCodes.LoadAsync(r);
}
private void AccountCodes_LoadCompleted(object sender, LoadCompletedEventArgs e)
{
if (_company.AccountCodes!= null && _company.AccountCodes.Count() > 0)
{
//do something. but right now it returns no record
}
}

Edit:
You can use Contains for pass a list of items for a database linq query:
.Where(x=> itemList.Contains(x.Code)).ToList()
Debugger escape characters:
As for the `\" part This is only the debugger showing the value like that.
Trying clicking the small magnifier icon or printing the value to the console, you'll get:
"11001-111001" || x.Code == "11016-111001" || "
See this image as a proof:
Those escape backslashes are added by the debugger only.
To add a single quote, you can use one of the below approaches:
string commaString = " \" "
Or:
string commaString = #" "" "

user3185569 is right. It's just the debugger that shows that value. Nevertheless it might not be the best idea to concatenate the strings that way (remember: strings are immutable). I would use a StringBuilder() and string.Format() as follows:
StringBuilder itemList = new StringBuilder();
for (int i = 0; i < TestList.Count; i++)
{
itemList.Append(string.Format("\"{0}\" || ", TestList[i].Code));
}
This also improves readability.

Related

ArgumentOutOfRangeException: extracting string from string

I have a method that extracts a username from a string using conditionals to check common conventions, although it is resulting in an ArgumentOutOfRangeException on the GetPart utility method, even after explicitly checking before calling it?
Here is the extraction method
public bool TryExtractUsernameFromString(string str, out string username)
{
if (str.Contains("un: "))
{
username = GetPart(str, "un: ", " ");
}
else if (str.Contains("un:"))
{
username = str.Split(" ").Where(x => x.StartsWith("un:")).First().Substring(3);
}
else if (str.Contains("un- "))
{
username = str.IndexOf(" ", str.IndexOf("un- ") + 1) > 0 ? GetPart(str, "un- ", " ") : str[str.IndexOf("un- ")..str.Length];
}
else if (str.Contains("un-"))
{
username = str.Split(" ").Where(x => x.StartsWith("un-")).First().Substring(3);
}
else
{
username = "";
}
return username.Length > 0;
}
I am passing this as the first argument to TryExtractUsernameFromString (without quotes)
"😊un- jennyfromtheblock"
So it happens here,
else if (str.Contains("un- "))
{
username = str.IndexOf(" ", (str.IndexOf("un- ") + 1)) > 0 ? GetPart(str, "un- ", " ") : str[str.IndexOf("un -")..str.Length];
}
But shouldn't be calling GetPart() if it doesn't contain a second space after the first one in the str.Contains check.
GetPart method:
public static string GetPart(string s, string start, string end)
{
return s[(s.IndexOf(start) + start.Length)..s.IndexOf(end)];
}
str.IndexOf("un- ") + 1 is returning the index of the START + 1 of that substring. Try using str.IndexOf("un- ") + 4 instead. That'll get you the index of the second space you're looking for.
#DanRayson looks correct; But I wanted to add there is likely a much cleaner approach to this.
If statements can suck, case statements aren't really better. If you assume any name could have 0 or more matches:
public static void CleanName(string nameString, List<string> badPrefixes)
{
var matchedPrefixes = badPrefixes.Where(w => nameString.Contains(w)
&& && nameString.IndexOf(w) == 0).ToList();
foreach(var prefix in matchedPrefixes)
{
Console.WriteLine(nameString.Replace(prefix, "").Trim());
}
if (!matchedPrefixes.Any())
{
Console.WriteLine(nameString);
}
}
Another option would be using .FirstOrDefault instead of selecting all of the matches. But essentially, just find the match(es) and then remove it, and finally trim spaces.
Example
public static void Main()
{
List<string> badPrefixes = new List<string>()
{
"un:",
"un-",
"un ",
"Un", //Fun example too
};
string longUserName1 = "un- Austin";
string riskyLongName = "un: theUndying";
CleanName(longUserName1, badPrefixes);
// output: Austin
CleanName(riskyLongName, badPrefixes);
// output: theUndying
}

How to check if multiple checkboxes are checked

So in my program, i have three checboxes (A, B and C). and I want to save the content of the checkbox the is checked to a text file. I am doing this using if statements as shown below:
if (a.IsChecked == true)
{
res = a.Content.ToString() + " is checked";
}
else if (b.IsChecked == true)
{
res = b.Content.ToString() + " is checked";
}
else if (c.IsChecked == true)
{
res = c.Content.ToString() + " is checked";
}
And here is where i am saving the above values to a string and then later in my code to a text file
string test = res;
Now this is working for me. So i decided to try to check if multiple checkboxes are being checked. So added the below if statements:
else if ((a.IsChecked == true) && (b.IsChecked == true) && (c.IsChecked == true))
{
res= a.Content.ToString() + " " + b.Content.ToString() + " " + c.Content.ToString()
}
but this isn't working with me because in the end res is printed in the text file as a rather than a b c. Any idea what i am doing wrong?
Also please note that i already initialized res at the top of my code as string:
string res;
I am not getting any error when i run my code so i am not sure where my mistake is. any help with this is much much appreciated.
thanks a lot :)
Its a good practice to use a StringBuilder in these cases.
On the other hand, if it is ok to have one line for each CheckBox, you can use the following:
StringBuilder sb = new StringBuilder();
checkappend(ref sb, a);
checkappend(ref sb, b);
checkappend(ref sb, c);
string res = sb.ToString();
in which
static void checkappend(ref StringBuilder sb, CheckBox ck)
{
sb.Append(ck.Content.ToString());
sb.Append(ck.IsChecked == true ? "is checked." : " is NOT checked.");
sb.Append(Environment.NewLine);
}
Note that creating a separate class can help you when there are many CheckBoxes in a List. You can simply use
foreach (var ck in listOfCheckBoxes)
checkappend(ref ck, c);
You can implement it this way:
string res = "";
if (a.IsChecked)
{
res += a.Content.ToString();
}
if (b.IsChecked)
{
res += b.Content.ToString();
}
if (c.IsChecked)
{
res += c.Content.ToString();
}
or simple
string res = $"{(a.IsChecked?a.Content+" ":"")}{(b.IsChecked?b.Content+" ":"")}{(c.IsChecked?c.Content:"")}";
That's multiple combinations to check. Simply remove else from first code snippet to run all checks one after another. You will get only report from last successful check, to have several reports you have to accumulate them somehow (add to a list, combine in multi-line string, etc.).
Here is a simple one-liner (using linq):
var result = string.Join(" and ", new[] { a, b, c }.Where(o => o.IsChecked).Select(o => $"{o.Content} is checked"));

Delimit string and put it in listbox

I have a string like:
one,one,one,one,two,two,two,two,three,three,three,three,four,four,four,four,...
and I'd like to delimit it after every fourth comma and store it into a list box, like this:
one,one,one,one,
two,two,two,two,
three,three,three,three,
four,four,four,four,
...
What should be appropriate way to do this? Should I supposed to use regex to somehow delimit this string?
Thanks
Linqless alternative;
int s = 0, n = 0, len = inputString.Length;
for (var i = 0; i < len; i++) {
if (inputString[i] == ',' && ++n % 4 == 0 || i == len - 1) {
aListBox.Items.Add(inputString.Substring(s, i - s + 1));
s = i + 1;
}
}
This LINQ breaks your input into individual strings by delimiting on the comma, then uses an index in the Select method to group four items together at a time, then finally joins those four items into a single string again.
var input = "one,one,one,one,two,two,two,two,three,three,three,three"; // and so on
var result = input.Split(',')
.Select((s, i) => new {s, i})
.GroupBy(pair => pair.i / 4)
.Select(grp => string.Join(",", grp.Select(pair => pair.s)) + ",");
The result is a collection of strings, where the first one (based on your input) is "one,one,one,one,", then the second is "two,two,two,two," and so on...
From there, it's just a matter of setting it as the DataSource, ItemsSource or similar, depending on what technology you're using.

append ". " after selected item values of checkbox list

I have a check box list item with List items in it. When i save the form selected values should be save to database .
See my logic.
string Type = null;
for (int i = 0; i < chbCourse.Items.Count; i++)
{
if (chbCourse.Items[i].Selected == true)
{
Type += chbCourse.Items[i].ToString() + ",";
}
}
It is working great but because of the "," which is i am putting between two values they are separated with each other, but at last item also it will append the "," . Is there any way to remove last "," or insert "." at last ","
Is there any logic for doing this?
Join all selected items, using string.Join and LINQ:
Type = string.Join(",",
chbCourse.Items.Cast<ListItem>().Where(x => x.Selected).Select(x => x.Text));
Since string.Join only adds the separator between items, it won't add an extra comma to the end.
(Also, calling ToString() on a ListItem displays the class type; you have to use the Text property.)
void Main()
{
var a="1,2,3,";
a=a.TrimEnd(new [] {','});
Console.WriteLine (a); //1,2,3
}
Do it like this for selected items:
string Type = string.Join(",", CheckBoxList1.Items.Cast<ListItem>().Where(a=>a.Selected).Select(a => a.Text));
if (!string.IsNullOrEmpty(Type)) // To add '.' at end
Type = Type + ".";
The easiest way is to use String.Join:
string Type = String.Join(",", chbCourse.Items);
If "." is also required
string Type = String.Concat(String.Join(",", chbCourse.Items),".");
If I'd wanted to put dot (".") on the last character, then I would do:
for (int i = 0; i < chbCourse.Items.Count; i++)
{
if (chbCourse.Items[i].Selected == true)
{
if (i == chbCourse.Items.Count - 1) Type += chbCourse.Items[i].ToString() + ".";
else
Type += chbCourse.Items[i].ToString() + ",";
}
}
string Type = null;
for (int i = 0; i < chbCourse.Items.Count; i++)
{
if (chbCourse.Items[i].Selected == true)
{
Type += chbCourse.Items[i].ToString() + ",";
}
}
if(Type != null)
Type = Type.TrimEnd(',');
Try not to use Class Names as variable names.
How about
string Type = null;
type = String.Join(",",
chbCourse.Items.Where(Function(x) x => x.Selected)
.Select(Function(y) y => y.ToString()).ToArray);

Problem calling string manipulation method within linq-to-sql query

I'm having a frustrating issue trying to use LINQ to call a string manipulation method. I've done lots of searching now and have tried various method to get the line noted as 'FAILS' below to work. It currently throws an exception.
Some things I've tried:
a) Initially the creation of the concatenated key was in the same query, didn't change anything
b) Converting the non-string fields to strings (another whole can of works with .ToString not working in linq. String.Concat and String.Format were tried, work ok in some cases but not when you try to refer to that value later on)
c) Using the concat etc instead of the '+' to join the things together.
As you can see it seems fairly tolerant of appending strings to non-strings, but not when that method is invoked.
There are lots of rows so I'd prefer not to convert the data to a list/array etc, but if that's the only option then any suggestions appreciated.
Many thanks! - Mark
var vouchers = from v in db.Vouchers
select new
{
v.Amount,
v.Due_Date,
v.Invoice_Date,
v.PO_CC,
v.Vendor_No_,
v.Invoice_No_,
invoiceNumeric = MFUtil.StripNonNumeric(v.Invoice_No_)
};
var keyedvouchers = from vv in vouchers
select new
{
thekey = vv.Vendor_No_ + "Test", // works with normal string
thekey2 = vv.Amount + "Test", // works with decimal
thekey3 = vv.Invoice_Date + "Test", // works with date
thekey4 = vv.invoiceNumeric, // works
thekey5 = vv.invoiceNumeric + "Test" // FAILS
};
-- The method to strip chars ---
public static string StripNonNumeric(string str)
{
StringBuilder sb = new StringBuilder();
foreach (char c in str)
{
// only append if its withing the acceptable boundaries
// strip special chars: if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') | || (c >= 'a' && c <= 'z') | c == '.' || c == '_')
// strip any nonnumeric chars
if (c >= '0' && c <= '9')
{
sb.Append(c);
}
}
return sb.ToString();
}
-- The Exception Message--
System.InvalidOperationException was unhandled by user code
Message=Could not translate expression 'Table(Voucher).Select(v => new <>f__AnonymousType07(Amount = v.Amount, Due_Date = v.Due_Date, Invoice_Date = v.Invoice_Date, PO_CC = v.PO_CC, Vendor_No_ = v.Vendor_No_, Invoice_No_ = v.Invoice_No_, invoiceNumeric = StripNonNumeric(v.Invoice_No_))).Select(vv => new <>f__AnonymousType15(thekey = (vv.Vendor_No_ + "Test"), thekey2 = (Convert(vv.Amount) + "Test"), thekey3 = (Convert(vv.Invoice_Date) + "Test"), thekey4 = vv.invoiceNumeric, thekey5 = (vv.invoiceNumeric + "Test")))' into SQL and could not treat it as a local expression.
It's because it tries to build an SQL query of the expression and the MFUtil.StripNonNumeric cannot be translated into SQL.
Try returning it first and then convert the reult into a list and then use a second query to convert it.
var vouchers_temp = from v in db.Vouchers
select new
{
v.Amount,
v.Due_Date,
v.Invoice_Date,
v.PO_CC,
v.Vendor_No_,
v.Invoice_No_
};
var vouchers = vouchers_temp.ToList().Select( new {
Amount,
Due_Date,
Invoice_Date,
PO_CC,
Vendor_No_,
Invoice_No_,
invoiceNumeric = MFUtil.StripNonNumeric(Invoice_No_)
});
It FAILS to work, because it is not suppose to work.
Create a SQL-side function and call that in the query.

Categories