C# – compare two string value


I'd like to compare two string values​​, like this:

if (lblCapacity.Text <= lblSizeFile.Text)

How can I do it?

Best Solution

I'm assuming that you are comparing strings in lexicographical order, in which case you can use the Static method String.Compare.

For example, you have two strings str1 and str2, and you want to see if str1 comes before str2 in an alphabet. Your code would look like this :

string str1 = "A string";
string str2 = "Some other string";
if(String.Compare(str1,str2) < 0)
   // str1 is less than str2
else if(String.Compare(str1,str2) == 0)
   // str1 equals str2
   // str11 is greater than str2, and String.Compare returned a value greater than 0

This above code would return yes. There are many overloaded versions of String.Compare, including some where you can ignore case, or use format strings. Check out String.Compare.