c# string Compare - c#

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

Related

Compare string null or empty in c#

In my table of MySQL Db I have the field Check.
The value memorized on the field Check it could be : null or -1.
When the value memorized on the field Check is null or -1 I need in return the xxx value. and I have tried :
string Check = sdr["Check"] == DBNull.Value || sdr["Check"] == "-1,00" ? "xxx" : sdr["Check"].ToString();
Without success because the output is always -1,00.
How to do resolve this?
Please help me, thank you so much in advance.
The problem is that you are comparing the wrong objects. The values returned from System.Data result sets are wrappers around the actual value. What you want are the typed versions. Basically, the check should look like this:
int checkIndex = sdr.GetOrdinal("Check");
string Check = sdr.IsDBNull(checkIndex) || (sdr.GetString(checkIndex) == "-1,00") ? "xxx" : sdr.GetString(checkIndex);
If you "Check" is actually a number, you may want to use the IntValue("Check") call, just to deal with globalization issues if your app is ever deployed where they use a "." instead of a "," for your decimal point.
See https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader(v=vs.110).aspx for the full API.
If your MySQL database is not set to use the same locale formatting as your C# application, your assumptions about number formats could be incorrect. To make a more robust version of your check, I would recommend something like this:
int checkIndex = sdr.GetOrdinal("Check");
string Check = "xxx";
double checkValue = sdr.IsDBNull(checkIndex) ? -1 : Convert.ToDouble(sdr[checkIndex]);
if (checkValue != -1)
{
Check = checkValue.ToString(CultureInfo.CurrentCulture);
}
If the data type is decimal 10,2 you need Convert.ToDecimal the value :
string Check = (sdr["Check"] == DBNull.Value || Convert.ToDecimal(sdr["Check"]) == -1) ? "xxx" : sdr["Check"].ToString();
You can compare a string empty or null by below code
string str = Your string
if(String.IsNullOrEmpty(str))
{
if yes, it comes here
}
else
{
if not, it comes here
}
The String.IsNullOrEmpty() is a bool type.

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 }

Why String.Equals is returning false?

I have the following C# code (from a library I'm using) that tries to find a certificate comparing the thumbprint. Notice that in the following code both mycert.Thumbprint and certificateThumbprint are strings.
var certificateThumbprint = AppSettings.CertificateThumbprint;
var cert =
myStore.Certificates.OfType<X509Certificate2>().FirstOrDefault(
mycert =>
mycert.Thumbprint != null && mycert.Thumbprint.Equals(certificateThumbprint)
);
This fails to find the certificate with the thumbprint because mycert.Thumbprint.Equals(certificateThumbprint) is false even when the strings are equal. mycert.Thumbprint == certificateThumbprint also returns false, while mycert.Thumbprint.CompareTo(certificateThumbprint) returns 0.
I might be missing something obvious, but I can't figure out why the Equals method is failing. Ideas?
CompareTo ignores certain characters:
static void Main(string[] args)
{
var a = "asdas"+(char)847;//add a hidden character
var b = "asdas";
Console.WriteLine(a.Equals(b)); //false
Console.WriteLine(a.CompareTo(b)); //0
Console.WriteLine(a.Length); //6
Console.WriteLine(b.Length); //5
//watch window shows both a and b as "asdas"
}
(Here, the character added to a is U+034F, Combining Grapheme Joiner.)
So CompareTo's result is not a good indicator of a bug in Equals. The most likely reason of your problem is hidden characters. You can check the lengths to be sure.
See this for more info.
You may wish to try using an overload of String.Equals that accepts a parameter of type StringComparison.
For example:
myCert.Thumbprint.Equals(certificateThumbprint, StringComparison.[SomeEnumeration])
Where [SomeEnumeration] is replaced with one of the following enumerated constants:
- CurrentCulture
- CurrentCultureIgnoreCase
- InvariantCulture
- InvariantCultureIgnoreCase
- Ordinal
- OrdinalIgnoreCase
Reference the MSDN Documentation found here.
Sometimes when we insert data in database it stores some spaces like "question ". And when you will try to compare it with "question" it returns false. So my suggestion is: please check the value in database or use Trim() method.
In your case, please try:
mycert.Thumbprint != null && mycert.Thumbprint.trim().equals(certificateThumbprint.trim())
I think it will return true if any record will exist.

If else minifier

I have many lines of code like this.. this is just a 1 thing i am trying right now.
if (RI2.Text.Contains("SOS") || RI2.Text.Contains("WAR"))
{
Response.Redirect("http://mydomain.com/rabat");
}
if (RI2.Text.Contains("sos") || RI2.Text.Contains("war"))
{
Response.Redirect("http://mydomain.com/rabat");
}
How do i minify this code. i mean, its very ugly and there many lines of code similar to this.
is there any better way of doing this which i dont know.
please help. appreciate your time and help.
Try this regular expression.
Ignores case in comparison (SOS and sos matched)
Does not mutate the strings as you don't call ToLower()
Only 2 lines of code
You can optionally precompile the expression if the expression (SOS|WAR) is a constant for more performance.
if (Regex.IsMatch(RI2.Text, "SOS|WAR", RegexOptions.IgnoreCase))
Response.Redirect("http://mydomain.com/rabat");
Not sure I fully understand your requirements, but here you go:
if(RI2.Text.ToLower().Contains("sos") || RI2.Text.ToLower().Contains("war")) {
Response.Redirect("http://mydomain.com/rabat");
}
you can do one call, like
//this will accept "SOS" and "sos"
if(RI2.Text.ToLower().Contains("sos") ||
RI2.Text.ToLower().Contains("war"))
{
....
}
You could convert the string to lowercase removing one if statement and then use a linq any statement.
var search=new[] {"sos","war"};
if (search.Any(x=>RI2.Text.ToLower().Contains(x))) {
Response.Redirect("http://mydomain.com/rabat");
}
Or even make collection of matches to target urls.
var search = new Dictionary<string,string>{
{"sos","http://mydomain.com/rabat"},
{"war","http://mydomain.com/rabat"},
};
The use linq
var url=search.Keys.Where(x=>RI2.Text.ToLower().Contains(x)).Select(x=>search[x]).FirstOrDefault();
if (url!=null) {
Response.Redirect(url);
}
You could create a extention to string as follows
public static bool Contains(this string value, string[] values)
{
foreach (string comparar in values)
{
if (value.ToUpper().Contains(comparar.ToUpper())) return true;
}
return false;
}
Instead of converting the string to lower or upper case use string.IndexOf with ignore case
if (RI2.Text.IndexOf("sos",StringComparison.InvariantCultureIgnoreCase) >= 0 ||
RI2.Text.IndexOf("war",StringComparison.InvariantCultureIgnoreCase) >= 0 )
{
Response.Redirect("http://mydomain.com/rabat");
}
if(string.Equals("war", RI2.Text, StringComparison.InvariantCultureIgnoreCase) ||
string.Equals("sos", RI2.Text, StringComparison.InvariantCultureIgnoreCase))
Response.Redirect("http://mydomain.com/rabat");
Create a list of string pairs, with one being the search string in upper case and the other being the redirect location.
Iterate through the list checking each search string against the upper-case text. If you find a match redirect to the location specified in the pair.
Use Regex:
var pattern = "(sos|war)";
if(Regex.IsMatch(RI2.Text.ToLower(), pattern))
Response.Redirect("http://mydomain.com/rabat");
Given that both the Url for Response.Redirect are same
string lowerRI2 = RI2.Text.ToLower();
if (lowerRI2.Contains("sos") || lowerRI2.Contains("war"))
Response.Redirect("http://mydomain.com/rabat");

Trim Method Doesn't Clear All Spaces

Hi i'm working on a basic windows form in c# and I have a little problem with the Trim() method.
There are 3 text boxes in witch the user enters his first name, last name and an ID.
Then he can save the info by clicking on a save button but I want to make sure that he doesn't leave blank boxes so I do the following test:
string CFN = Curator_FN.Text;
string CLN = CURATOR_LN.Text;
string CID = CURATOR_ID.Text;
Curator_FN.Text.Trim();
CURATOR_ID.Text.Trim();
CURATOR_LN.Text.Trim();
if (((Curator_FN.Text.Length == 0) || (CURATOR_ID.Text.Length == 0) || (CURATOR_LN.Text.Length == 0)))
{
MessageBox.Show("You Have to enter a First Name, a Last Name and an ID");
Empty = true;
}
The problem is if I just make some blank space with the space bar the Trim() method doesn't consider them as a blank space..
Maybe I just misunderstand the Trim() method and if I do, do you have any idea on how I could do the this?
Thanks in advance.
The Trim method does not modify the contents of the text boxes, it simply returns the trimmed version. You need to store this version, for example
Curator_FN.Text = Curator_FN.Text.Trim();
Of course this has the potential to make changes visible to the user (and it also has to access the UI thread which under other circumstances might be a problem), so it is far better to use a local variable as in
var curatorFn = Curator_FN.Text.Trim();
// etc
if (curatorFn.Length == 0 || ... ) {
// show messagebox
}
Of course if this is all you need to do, using string.IsNullOrWhiteSpace might be a more convenient alternative.
Since strings are immutable in C#, the Trim() method doesn't change the string itself; it returns a new instance of the trimmed string.
You need to assign the results of the method calls to the variables, i.e.
CFN = Curator_FN.Text.Trim()
And then check whether or not CFN is empty.
Trim does not modify the string. You want:
Curator_FN.Text = Curator_FN.Text.Trim();
CURATOR_ID.Text = CURATOR_ID.Text.Trim();
CURATOR_LN.Text = CURATOR_LN.Text.Trim();
Also, if you're using .NET 4 you might want to check into the String.IsNullOrWhiteSpace method as well.
if (String.IsNullOrWhiteSpace(Curator_FN.Text) ||
String.IsNullOrWhiteSpace(CURATOR_ID.Text) ||
String.IsNullOrWhiteSpace(CURATOR_LN.Text)
{
//..
}
Trim does not modify the string itself. It returns a new trimmed string.
If you don't really care about modifying the variable, look at the IsNullOrWhiteSpace method.
if (String.IsNullOrWhiteSpace(curatorFn) || ... ) {
// show messagebox
}

Categories