运算符'> ='不能应用于类型为'string'和'string'的操作数 [英] Operator '>=' cannot be applied to operands of type 'string' and 'string'

查看:660
本文介绍了运算符'> ='不能应用于类型为'string'和'string'的操作数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在C#中使用Entity Framework,而我的代码是

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();

这给了我这个错误:

运算符'> ='不能应用于类型为'string'和'string'的操作数

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

如何比较两个字符串并修复错误?

How to compare two string and fix the error?

推荐答案

比较数字时,说1和2,很明显哪个更大.但是,比较字符串时,哪个更大:"2"或"11"? "foo"还是"f"?答:这取决于上下文.例如,如果按字典顺序对它们进行排序,则会得到"2"和"f".如果您想要自然排序,则可以在"11"之前获得"2".

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()

要使代码不受文化限制而工作(您应该!),请提供StringComparison作为string.compare的最后一个参数:

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)

这篇关于运算符'&gt; ='不能应用于类型为'string'和'string'的操作数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆