String comparision not working correctly? - c#

I'm using this library to hook keys and I have some problems with comparing e.KeyCode.ToString() with same string.
I have variable which is string equivalent of
Keys.Oemtilde ->
Program.KeyboardTradeHotkey = "Oemtilde";
I keep it in string because I read that string from xml file and I can't seem to get any way to convert string to Keys.
If i use it this way:
if (e.KeyCode.Equals(Keys.Oemtilde)) {
Logging.AddToLog("[Keyboard][Check] " + e.KeyCode);
} else {
// failed to catch - executes else
Logging.AddToLog("[Keyboard][PRESS]");
}
It works fine and: Logging.AddToLog("[Keyboard][Check] " + e.KeyCode); is executed.
If i use it:
if (e.KeyCode.ToString() == Program.KeyboardTradeHotkey) {
Logging.AddToLog("[Keyboard][Check] " + e.KeyCode);
} else {
// failed to catch - executes else
Logging.AddToLog("[Keyboard][PRESS]");
}
It executes else clause. It seems like String Compare doesn't really works in this case even thou both string (e.KeyCode.ToString() and Program.KeyboardTradeHotkey are the same.
What can be the reason for this?

another change make use of string.Equals function to compare string
string1.Equals(string2)

I think it is because KeyCode.ToString() doesn't return what you expect it to return. Look at the view in a Watch.

Without having to look at the library that you are using the first (working) code sample looks like it is comparing enum values, so it is returning a number instead of a string.

The difference between == and .Equals() is because of the differences between reference types and value types. This link gives examples of the different results: Comparison of == and .Equals()
I also agree with pranay_stacker.

Related

C# Check List against part of string

I have a list which contains values such as:
readies action
uses action
begins to cast action
I want to compare a string to match against this list and return a boolean based on that. So for example:
string compare = "The Manipulator uses action";
To do this I have tried two different methods, the first being:
if (mylist.Contains(compare)) { //True }
and the second (with Linq):
if (mylist.Any(str => str.Contains(compare))) { //True }
The problem I'm having is both of these methods match against an extended string. What I mean by that is if compare == "uses action" the statement returns true, but if compare == "The Manipulator uses action" the statement returns false.
Any help on fixing this would be most appreciated! :)
I'm not totally following what you're looking for, so there are 2 different solutions, besed on expected outcome.
If you're only trying to match exactly the same string from within the list Any is the way to go, but you should use == instead of Contains:
if (mylist.Any(str => str == compare)) { //True }
If you'd like extended string to also match, you use Contains, but instead of calling str.Contains(compare) call compare.Contains(str):
if (mylist.Any(str => compare.Contains(str))) { //True }

C# If Equals Case insensitive [duplicate]

This question already has answers here:
Comparing two strings, ignoring case in C# [duplicate]
(8 answers)
Closed 9 years ago.
The following code will open up a Message Box containing the word "Fail".
Is there a way to make the if statement case insensitive, so that the if statement passes and opens a mbox containg "Pass" without converting the character/string to upper/lower case?
here is the code:
public partial class Form1 : Form
{
string one = "A";
string two = "a";
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (one == two)
{
MessageBox.Show("Pass");
}
else
{
MessageBox.Show("Fail");
}
}
}
Thanks in advance
You could use this
string.Equals(one, two, StringComparison.CurrentCultureIgnoreCase)
Your code would be
if (string.Equals(one, two, StringComparison.CurrentCultureIgnoreCase))
{
MessageBox.Show("Pass");
}
else
{
MessageBox.Show("Fail");
}
Using CurrentCultureIgnoreCase :
Compare strings using culture-sensitive sort rules, the current
culture, and ignoring the case of the strings being compared.
More info here
if (string.Equals(one, two, StringComparison.CurrentCultureIgnoreCase))
From MSDN:
StringComparer.CurrentCultureIgnoreCase Property
Gets a StringComparer object that performs case-insensitive string comparisons using the word comparison rules of the current culture.
Various options:
if (String.Compare(one, two, StringComparison.CurrentCultureIgnoreCase) == 0) {
// they are equal
}
Option 2:
if ((one ?? "").ToLower() == (two ?? "").ToLower())
// they are equal
}
There are tons of other options, but these should get you started!
NOTE - One thing people regularly forget with string comparisons is null values. Be sure to watch for null values however you do your comparison. The second option I presented does an excellent job of this.
Use a case insensitive string comparer:
if(StringComparer.OrdinalIgnoreCase.Equals(one, two))
You should also consider if this comparison needs to be done in the user's culture.
You should use .Equals() to compare strings. Then you can use StringComparison.OrdinalIgnoreCase as the third argument to ignore case.
You can as well use this
string one = "obi";
string two = "Obi";
if(one.Equals(two, StringComparison.OrdinalIgnoreCase))
{
/* Your code */
}
if(one.ToLower() == two.ToLower())
{
//Do stuff
}

c# string Compare

I am trying to create list filter in .net MVC4 C#.
I have ajax query that sends string to controller and according to matches in database it returns number of records.
So when the String is IsNullOrEmpty() and IsNullOrWhiteSpace() it brings me fine result.
I have problem in matching values now.
Although it seemed me easy so i tried-
Controller
public ActionResult SearchAccountHead(string accountHead)
{
var students = from s in db.LedgerTables
select s;
List<LedgerModel> ledge = null;
if (!String.IsNullOrEmpty(accountHead))
{
//Returns non-empty records
}
if (String.IsNullOrEmpty(accountHead) && String.IsNullOrWhiteSpace(accountHead))
{
//Checks whether string is null or containing whitespace
//And returns filtered result
}
return PartialView(ledge);
}
Now if I have string that doesn't match with string I have been using in controller then I tried mapping it-
if (String.IsNullOrEmpty(accountHead) && String.IsNullOrWhiteSpace(accountHead) && !String.Compare(accountHead))
if (String.IsNullOrEmpty(accountHead) && String.IsNullOrWhiteSpace(accountHead) && !String.Compare(AccountHead,ledge.AccountHead))
But in both cases it didn't work.
How can I get into second method when string doesn't match?
You can't apply string.Compare with !, since string.Compare would return an integer value. If you are comparing string for equality then its better if you use string.Equals, it also has an overload which does case insensitive comparison.
You can have the check like:
if (String.IsNullOrWhiteSpace(accountHead) &&
!String.Equals(AccountHead, ledge.AccountHead,StringComparison.InvariantCultureIgnoreCase))
As a side note you can remove
if (String.IsNullOrEmpty(AccountHead) && String.IsNullOrWhiteSpace(AccountHead))
and just use
if (String.IsNullOrWhiteSpace(AccountHead))
since string.IsNullOrWhiteSpace checks for empty strings as well.
You can use string.Equals() and pass it an option for comparison logic. Something like this:
AccountHead.Equals(ledge.AccountHead, StringComparison.InvariantCultureIgnoreCase)
This will compare AccountHead and ledge.AccountHead in a case-insensitive manner using invariant culture rules. There are additional options to choose from as well.
You can use String.Compare to do the same as String.Equals, however, it's a bit less succinct e.g.
String.Compare(AccountHead, ledge.AccountHead, StringComparison.OrdinalIgnoreCase) <> 0
Here's the shorter way...
!AccountHead.Equals(ledge.AccountHead, StringComparison.OrdinalIgnoreCase);
You can keep it simple and write something like this !(accountHead == ledge.AccountHead).
You don't need comparison as i see, but to check if strings are equal or not. Usually Equals is the best way to do that, but "==" does semantic and object.ReferenceEquals -- referential comparison. So i would go with that one.
Hope this helps

can this trim code ever fail?

I recently bumped into an exception in my code because I was trimming a null string.
I replaced it with the following:
SomeValue = (SomeString ?? "").Trim();
Can this code ever fail?
Thanks.
Note: I know I can add a try/catch; I'm just looking to make this line fail-proof without using a try/catch.
This will not fail (ie. throw a NullReferenceException), assuming SomeString is indeed a string.
You could achieve the same in many ways:
SomeValue = (SomeString == null)?string.Empty:SomeString.Trim();
It's not the way I would have done it, but no, this shouldn't ever fail now.
I'd probably write an extension method that calls trim after checking for null. Something like this:
public static string NullTrim(this String str) {
if(str == null) {
return string.Empty;
}
return str.Trim();
}
This allows all of the following to compile and execute without error:
"".NullTrim();
" test ".NullTrim();
((string)null).NullTrim();
Well if it was failing because of NullReferenceException, then now it will definitely not fail because of that. As for the rest, I cannot say without context.

Querystring - Add values to querystring in c#

How can I add values to querystring?
I'm trying to do this:
String currurl = HttpContext.Current.Request.RawUrl;
var querystring = HttpContext.Current.Request.QueryString.ToString();
var PrintURL = currurl + (String.IsNullOrEmpty(querystring)) ?
HttpContext.Current.Request.QueryString.Add("print", "y") : string.Empty;
But I keep getting this error:
Cannot implicitly convert type 'string' to 'bool'
all i'm trying to do is get current url and add ?pring=y to querystring
Well, the first problem can be solved using this instead:
var PrintURL = currurl + (String.IsNullOrEmpty(querystring) ?
HttpContext.Current.Request.QueryString.Add("print", "y") : string.Empty);
All that's changed from your original code is simply moving the closing paren from (String.IsNullOrEmpty(querystring)) (where it was unnecessary) to the end of the ?: clause. This makes it explicitly clear what you're trying to do.
Otherwise, the compiler tries to concatenate the result of String.IsNullOrEmpty(querystring) (which is a bool) to currUrl -- incorrect, and not what you intended in the first place.
However, you've got a second problem with the HttpContext.Current.Request.QueryString.Add("print", "y") statement. This returns void, not a string. You'll need to modify this part of your ternary expression so that it returns a string -- what are you trying to do?
HttpContext.Current.Request.QueryString.Add("print", "y") returns void, not a string, so you can't use that call in the ternary expression. Plus, adding to the querystring on the Request won't affect your HTTPResponse, and I'm assuming that's what you want to do. You need to craft the new URL and use response.redirect to have the browser load the new url with the updated querystring.
i figured it out.
String currurl = HttpContext.Current.Request.Url.ToString();
String querystring = null;
// Check to make sure some query string variables
// exist and if not add some and redirect.
int iqs = currurl.IndexOf('?');
if (iqs == -1)
{
String redirecturl = currurl + "?print=y";
}
not sure if this is the cleanest way but it works.
thanks all for help
There's a couple things wrong here with what you're trying to do.
The first thing is that the QueryString collection is a NameValueCollection. The Add method has a void return. So even trying to assign the result of QueryString.Add isn't going to work.
Second, you can't modify the QueryString collection. It's read-only. There's a response over on Velocity Reviews that talks to exactly what you're trying to do. Instead of trying to modify the query string, you should redirect the user with the new value.
currurl + (String.IsNullOrEmpty(querystring)
has to return a boolean so condition has to be different.
First problem is you need brackets around your statement that is using the ?:
var PrintURL = currurl + ((String.IsNullOrEmpty(querystring)) ? HttpContext.Current.Request.QueryString.Add("print", "y") : string.Empty);
The next problem is that HttpContext.Current.Request.QueryString.Add does not return anything so one side of the : returns void where the other returns and empty string.

Categories