I'm using Entity Framework in C# and my code is
var result = ef.services.Where(entry => entry.tarikhservice >= textBoxX1.Text
&& entry.tarikhservice <= textBoxX2.Text).ToList();
which gives me this error:
Operator '>=' cannot be applied to operands of type 'string' and 'string'
How to compare two string and fix the error?
When you compare numbers, say 1 and 2, it is clear which one is greater. However, when you compare strings, which one is considered greater: "2" or "11"? "foo" or "f"? Answer: it depends on context. For example if you sort them lexicographically, you get "2" and "f". If you want the natural sort, you would get "2" before "11".
I presume for that reason, relative operators (>, >=, <, <=) are not overloaded for string (which IMHO is a good decision).
Your option is to either write your custom logic to compare strings, or use a framework-provided lexicographical comparison. The code would be (if I got the numbers right):
var result = ef.services.Where(entry =>
string.Compare(entry.tarikhservice, textBoxX1.Text) >= 0
&& string.Compare(entry.tarikhservice, textBoxX2.Text) <= 0
.ToList()
To make code work regardless of culture (you should!), provide a StringComparison as last parameter to string.compare:
string.Compare(entry.tarikhservice, textBoxX1.Text, StringComparison.InvariantCulture)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With