Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operator '>=' cannot be applied to operands of type 'string' and 'string'

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?

like image 697
Mohammadreza Noori Avatar asked Feb 18 '15 11:02

Mohammadreza Noori


Video Answer


1 Answers

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)
like image 110
ya23 Avatar answered Oct 03 '22 15:10

ya23