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

c# entity-framework-6

Question

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?

1
8
3/4/2015 5:48:18 AM

Popular Answer

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)
20
2/18/2015 12:49:30 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow