How to cast a database entry to String - c#

if((string)row["ProductID"].ToString() == txtBarcode.Text)
I want to search a row if the value of the txtbox is the same as my datatable but i have an error.. it says that Possible unintended reference comparison; to get a value comparison, cast the left hand side to string. i just use .ToString() and Convert.ToString() but still have that error.

Your .ToString() is converting the row value to a string, so you don't also need to cast it on the left with (string)
Ie. if(row["ProductID"].ToString() == txtBarcode.Text)
Personally, I'd stare clear of using == operator with anything but ints, chars and whether this instance is that instance.
A better way of comparing strings is to use string.Equals(string) string.contains(string) or string.indexOf(string)

Note : if you are comparing with TextBox value then it is better to trim the values before comparing to remove the whitespaces using Trim() method.
Solution 1: if you want to find the excat match then you need to use Equals() method.
if(row["ProductID"].ToString().Equals(txtBarcode.Text.Trim())
{
/* do something*/
}
Solution 2: if you want to find the part of the string then you can use String.Contains() method as below:
if(row["ProductID"].ToString().Contains(txtBarcode.Text.Trim())
{
/* do something*/
}

You need to do one of the above. Either do a cast (string)row["ProductId"] or Convert.ToString(row["ProductId"]) for converting the value to string. But casting using (string)row["ProductId"] is likely to throw InvalidCastException. So may be ToString() would be better.

Related

C# Dynamic Linq: Strings are assumed to be integers?

I'm using the System.Linq.Dynamic library found here, which is simply an upload of Microsoft's library to be accessible via NuGet: https://github.com/kahanu/System.Linq.Dynamic
In my code, I have this function that gets a list of objects from a database that match a certain property. It needed to be as flexible as possible, so the parameters consist of three strings;
One for the "order by" statement
One for the property to match's name
One for the expected property's value
Here's the line of code that's giving me trouble:
public IQueryable<T> GetByProperty(string propertyName, string propertyValue,
string orderStatement)
{
return _context.Set<T>()
.OrderBy(orderStatement)
.Where(propertyName + " = " + propertyValue);
}
Here are the possible scenarios;
propertyValue contains only numbers: the query works perfectly.
propertyValue starts with numbers but has letters in it: the following error appears: Operator '=' incompatible with operand types 'String' and 'Int32'
propertyValue is anything else: the following error appears: No property or field '[the first part of the "propertyValue string, up until it meets an empty space, a "-" or some other specific characters]' exists in type '[Class name of <T>]'
I've tried using single quotes to surround my string, but I then get the error: 'Character literal must contain exactly one character'
I've also desperately tried to add ".ToString()" at the end to try and trick something into working, but I found the error: Digit expected.
Is there another way to use the "Where" clause, in Linq and Dynamic Linq, that would support the flexibility I'm trying to have using this structure?
You need to know the type of the property and format the value accordingly. If it is a string, enclose it in double quotes. i.e. name = "John" but age = 20.
It does not depend whether the value looks like a number or not.
If the type of the property is a number type then the value must be a number as well and not be enclosed in quotes.
If the type of the property is a string then the value must be enclosed in double quotes, even if the value is a number (e.g. code = "3").

How to Compare localized strings in C#

I am doing localization for ASP.NET Web Application, when user enters a localized string "XXXX" and i am comparing that string with a value in my localized resource file.
Example :
if ( txtCalender.Text == Resources.START_NOW)
{
//do something
}
But When i do that even when the two strings(localized strings) are equal, it returns false. ie.
txtCalender.Text ="இப்போது தொடங்க"
Resources.START_NOW="இப்போது தொடங்க"
This is localized for Tamil.
Please help..
Use one of the string.Equals overloads that takes a StringComparison value - this allows you to use the current culture for comparison..
if ( txtCalender.Text.Equals(Resources.START_NOW, StringComparison.CurrentCulture))
{
//do something
}
Or, if you want case insensitive comparison:
if ( txtCalender.Text.Equals(Resources.START_NOW,
StringComparison.CurrentCultureIgnoreCase))
{
//do something
}
I found the answer and it works. Here is the solution,
it was not working when i tried from Chrome browser and it works with Firefox. Actually when i converted both string to char array,
txtCalender.Text Returns 40 characters and Resource.START_NOW returned 46. So i have tried to Normalize the string using Normalize() method
if(txtCalender.Text.Normalize() == Resources.START_NOW.Normalize())
It was interpreting one character as two different characters when i didn't put normalize method.
it has worked fine. Thanks for your answers.
You can compare with InvariantCulture in String.Equals (statis method):
String.Equals("XXX", "XXX", StringComparison.InvariantCulture);
Not sure whether this helps though, could others comment on it? I've never come across your actual error.
Use String.Equals or String.Compare.
There is some performance differences between these two. String.Compare is faster than String.Equal because String.Compare is static method and String.Equals is instance method.
String.Equal returns a boolean. String.Compare returns 0 when the strings equal, but if they're different they return a positive or negative number depending on whether the first string is before (less) or after (greater) the second string. Therefore, use String.Equals when you need to know if they are the same or String.Compare when you need to make a decision based on more than equality.
You probably need to use .Equals
if(txt.Calendar.Text.Equals(Resources.START_NOW))
{ //...
And if case-insensitive comparison is what you're after (often is) use StringComparison.OrdinalIgnoreCase as the second argument to the .Equals call.
If this isn't working - then can I suggest you breakpoint the line and check the actual value of Resources.START_NOW - the only possible reason why this equality comparison would fail is if the two strings really aren't the same. So my guess is that your culture management isn't working properly.

Is it better to use "0" concatenation in Convert.ToInt32() function call

Is better to use the below statement
Convert.ToInt32("0" + stringValue)
If not then why?
I know that it is better to user int.TryParse() function, which is better, but what about the above statement.
Better than what?
Personally, I think that using Convert.ToInt32("0" + stringValue) is an anti-pattern.
It doesn't provide anything useful, since:
A positive integer will still result in the same value.
If you pass it a negative number, it will throw.
It doesn't add any extra error checking
It DOES create an extra string concatenation, which is not used for anything, reducing performance for no reason
It adds extra complexity for no reason.
Just use Convert.ToInt32(stringValue) directly, or int.TryParse if you don't want to have exception handling in place.
The only case when that would have any use is if the string variable is a null reference. Concatenating with a zero character is totally pointless, though. As we are only after the null check performed by the string concatenation, a better version would concatenate with an empty string instead, as that doesn't break for negative values:
Convert.ToInt32(String.Empty + stringValue)
A better solution as it doesn't do a string concatenation:
Convert.ToInt32(stringValue ?? String.Empty)
An even better solution would be to check for the null value first, so that you don't have to parse the known string:
stringValue == null ? 0 : Convert.ToInt32(stringValue)

In C# VS2008 how to replace (string)aaa to aaa.ToString()

I just converted a VB.net solution into C# solution. But lots of variables have been coverted like:
string var1 = (string)1;
string var2 = (string)intVar; //intVar is a int value
I just want to convert all (string)XXXX to XXXX.ToString() by using some Regular expressions or some other replace methods.
Can someome help me out?
find: \(string\){:a*}
replace: \1.ToString()
Back up your solution first!
The text editor Notepad++ has regular expression support. You may try something like: Replace [(]string[)][ ]*([^ .\t;/]*) with \1.ToString().
This turns this:
(string) xyz;
(string) abc.123;
(string)alf;
(string)argu ment
into this:
xyz.ToString();
abc.ToString().123;
alf.ToString();
argu.ToString() ment
This however, does not handle the case of (string) aFunction( obj1, obj2 ).
You may want to handle these by yourself first, or build another regexp.
I am not sure if you really want to do this as a mass conversion. As in all reality in your example, you should end up with the following.
string var1 = "1";
and
string var2 = intVar.ToString();
There is no need for your first example to be doing a cast, when it can be a string from the beginning.
Suggest you to use this one
Find: \(string\){(.*)}{:Po}
Replace: \1.ToString()\2
Good luck!
I am not too familiar with regex but I offer a warning instead. You might not want to replace all (string)xxx to xxx.toString() because (as you know I am sure) (string) is casting and a ToString() is a method call. You can only cast something as string if the object is a descendant of string. You can call ToString() if the implementor of the class overrode the ToString() method. If not then you are just going to get the default implementation.
Well, the reason that you get the extra code in the conversion, is that you don't have Option Strict On in the VB code. If you had, you wouldn't be able to do those implicit conversions in the first place.
So, the VB code should look like this, and the C# code would then look right in the conversion:
var1 As String = "1"
var2 As String = intVar.ToString
To fix this after the conversion is done is quite beyond what a regular expression is capable of. Sure, you could make an expression that would convert all (string)x to x.ToString(), but that would probably cause more problems that it fixed...

Simple way to trim Dollar Sign if present in C#

I have a DataRow and I am getting one of the elements which is a Amount with a dollar sign. I am calling a toString on it. Is there another method I can call on it to remove the dollar sign if present.
So something like:
dr.ToString.Substring(1, dr.ToString.Length);
But more conditionally in case the dollar sign ever made an appearance again.
I am trying to do this with explicitly defining another string.
Convert.ToString(dr(columnName)).Replace("$", String.Empty)
--
If you are working with a data table, then you have to unbox the value (by default its Object) to a string, so you are already creating a string, and then another with the replacement. There is really no other way to get around it, but you will only see performance differences when dealing with tens of thousands of operations.
You could also use
string trimmed = (dr as string).Trim('$');
or
string trimmed = (dr as string).TrimStart('$');
If you are using C# 3.0 or greater you could use extension methods.
public static string RemoveNonNumeric(this string s)
{
return s.Replace("$", "");
}
Then your code could be changed to:
((String)dr[columnName]).RemoveNonNumeric();
This would allow you to change the implementation of RemoveNonNumeric later to remove things like commas or $ signs in foreign currency's, etc.
Also, if the object coming out of the database is indeed a string you should not call ToString() since the object is already a string. You can instead cast it.
Regex would work.
Regex.Replace(theString, "$", "");
But there are multiple ways to solve this problem.
dr[columeName].ToString().Replace("$", String.Empty)
Why don't you update the database query so that it doesn't return the dollar sign? This way you don't have to futz with it in your C# code.

Categories

Resources