How to compare in IF condition - c#

I am returning a value from SQL. Let's give it a name as ReturnedFromSQL. In my application, I am giving an input. Let's give it a name as Input. I want to compare these two and do an activity. Currently, I am doing this with an IFcondition.
Let's say, from SQL I am getting FAB01and as the Input I am getting Fab01. What I want to do is to jump to ELSEpart after comparing these two if these two are not same and execute IF part if these two are same.
It is obvious that just the letters have changed but the idea is same. Since these two are same, I need to execute what is in IFpart instead of jumping to ELSE. But it is not happening now. How do I do that? Can anyone help me? Thank you in advance.
IF (ReturnedFromSQL == Input )
{
return RedirectToAction("Exist");
}
else
{
//Doing Something
}

Assuming that both ReturnedFromSQL and Input are strings. This code will convert both the value to lower for comparison so no issue if any of the string has same character but in different level(upper/lower)
if (ReturnedFromSQL.ToLower().Trim() == Input.ToLower().Trim() )
{
return RedirectToAction("Exist");
}
else
{
//Doing Something
}

You can use string.Equals(). The best part is that you do not need to trim or lowercase explicitly.
if(string.Equals(ReturnedFromSQL, Input, StringComparison.CurrentCultureIgnoreCase))
{
return RedirectToAction("Exist");
}

Take care if you follow the advice in some of the other answers. ToLower() is only safe in English and a handful of other languages. In many languages, there may be multiple upper/lower case representations of the same letter or letter combination, or certain accents may be considered equal or not equal, breaking such logic. There be the dragons.
Try this instead, changing the StringComparison as per your use case:
using System;
public class Program
{
public static void Main()
{
string ReturnedFromSQL = "FAB01";
string Input = "Fab01";
if (String.Equals(ReturnedFromSQL, Input, StringComparison.CurrentCultureIgnoreCase))
{
Console.WriteLine("Equal");
}
else
{
Console.WriteLine("Different");
}
}
}

if both values are string then you can apply ToLower() and Trim() (as in x.Trim().ToLower()) functions on both party in order to have a unified value. but even without that you still should be good, so i guess the problem is something else. i advise debugging the condition and check the value of both sides and see if either one is null or empty.

Your condition can use Equals
if (String.Equals(ReturnedFromSQL, Input, StringComparison.OrdinalIgnoreCase))

Related

SignalR bot only checks for exact case message.Contains. What about misspellings?

I have a bot that will respond to certain trigger words
if (message.Contains("trigger"))
{
HandleTrigger(message);
return ;
}
How can I foolproof this concept with a way to allow misspellings like 'triger' or 'triggr' So that it will still hit this breakpoint and return HandleTrigger(message);
More code for context:
void HandleTrigger(string message)
{
if (message.Contains("trigger2"))
{
ReplyMessage(viewTriggerMessage);
ReplyMessage(repeatMessage);
return;
}
if (message.Contains("trigger3"))
{
ReplyMessage(anotherMyTriggerMessage);
return;
}
Your question does not seem to be a SignalR question. It is more about matching misspelled words. There is an algorithm called the Double Metaphone that you can use to match misspelled words. It works on the principles of a phonetic match. You can read more on the algorithm here http://en.wikipedia.org/wiki/Metaphone#Double_Metaphone
You can find a C# implementation on this link. https://code.google.com/p/doublemetaphone/
Once you add the class from the above link to your project, you get an extension method to String variables called GenerateDoubleMetaphone()
And then you can compare the metaphones to check for similarity. In your example, you can write your if condition like this
if ("trigger".GenerateDoubleMetaphone().Equals(message.GenerateDoubleMetaphone()))
{
//Execute code for a match
}
In the example above the metaphones for "trigger" and "trigr" are both "TRKR" and hence will match.
You can also use Soundex algorithm code to generate a simple output that can be categorized correctly.
This is mostly used in an SQL database for finding strings that are similarly spelled.
Console.WriteLine(Soundex.For("Trigger")); //outputs 'T626'
Console.WriteLine(Soundex.For("Triggr")); //outputs 'T626'
https://dotnetfiddle.net/6OhjLT

C# read and react to a text string

assume that there is a string named "message", and assume an user type in the console,
"!My FB List", but words "FB" and "List" could be change. But "!My" won't change. So, I want to save the text the user type. Only if user used "!My" before the other words.
So, I don't know how to get this to 'if' command. Plz help me.
if (message == "!My "
Do you mean something like this?
if (message.StartsWith("!My "))
{
// do something
}
This code works in most situations. However, if you need to resolve situations like Kshitij Mehta mentioned in the comments, you'd be probably better off with a Split method parsing the string and comparing the first object of the array to the required string.
When you've split the input string into an array, you will just compare strings in a typical fashion (==), probably no need for fancy methods in that scenario.
One more "however" to consider - if your input string is long, splitting might not be the best idea to do. In that case I'd probably use regular expressions to compare the beginning of the inputted string.
The implementation depends on your needs. Just pick what suits you the best :)
It sounds like you want to accept commands and then do specific things based on those commands. Apparently, the "command" is the first word in the text typed by the user.
Thus, I'd split the message at whitespace and then switch for the first word:
var words = message.Split();
var command = words[0];
switch (command) {
case "!My":
// Do something
...
break;
case "!SomethingElse":
// Do something else
...
break;
...
}
Afterwards, you can use words[1] to get "FB" and words[2] to get "list". Be sure to use words.Length to verify if the required number of parameters has been specified before trying to access them.
String class includes many static methods, among which is StartsWith().
so your if statement can simply be
if(UserString.StartsWith("!My"))
{
// other conditional code here
}
It is not clear from your question whether you want to include cases where the user types "!My" before typing anything else, but he/she does NOT type a space immediately after typing !My.
If you only want to process the code if the three characters "!My" were followed by a space, then, (as suggested by #Walther), add a space to the test string in the StartsWith() method
if(UserString.StartsWith("!My "))
{
// other conditional code here
}

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.

Creating a regex to check for a strong password

Say I have a regex that checks for alphanumeric.
I now want to create another regex that checks for at least 1 number in the password.
And I want to check if it has at least 1 non-alphanumeric character (somethign other than a letter or number).
Should I just call each one seperatley, and if one fails return false or is there a way to combine them into 1 call?
Depends on exactly what criteria you're using, but it would probably be better to do a single pass through the string and set a number of flags based on what you've seen:
hasDigit
hasAlpha
hasSymbol
etc
Then use these at the end to decide if the password is complex enough.
Even Better:
As lexu suggests, using counts instead of flags would allow greater flexibility.
I would compose small methods using &&:
internal bool HasDigit(string password) { .. }
internal bool HasNonAlpha(string password) { .. }
bool IsStrong(string password) {
return HasDigit(password) && HasNonAlpha(password);
}
I think this is what you're looking for:
^.{6,}(?<=\d.*)(?<=[^a-zA-Z0-9].*)$
(will match a password with a minimum length of 6, with at least one digit and one non-alphanumerical character)
In code:
public bool PasswordOk(string pwd)
{
return Regex.IsMatch(pwd,#"^.{6,}(?<=\d.*)(?<=[^a-zA-Z0-9].*)$");
}
You should use two calls. For a bit more advanced testing you can use The password meter. It is freely available for distribution under GPL.
IMHO, it's a question of style whether to make one or two statements from it.
Why not check for it in any of the two orders that they may appear. (As regular expressions go, we don't have something like a counter for braces or parantheses, thus we have to honor the possible ordering of things.
That one might work for perl:
(\d.*[^[:alnum:]])|([^[:alnum:]].*\d)
Might be easier to read to make two statements from it, especially because then every semantical condition is only occurring once.
You add an | (or) operator into the regex e.g.
[0-9]|[A-Z]
Regex is not the fastest way.
Give this a try:
string Password = "Pass12!";
bool ValidPassword = Password.Any(char.IsDigit)
&& !Password.All(char.IsLetterOrDigit)
&& Password.Length >= 6;
Instead of:
string Password = "Pass12!";
bool ValidPassword = Regex.IsMatch(Password, #"^.{6,}(?<=\d.*)(?<=[^a-zA-Z0-9].*)$");
I you iterate through it 1 million times it will take the first 157ms and the second 1251ms.
And the most important thing the others said already: much better to maintain.

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