问题描述
我在 C# 中使用实体框架,我的代码是
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)
这篇关于运算符“>="不能应用于“字符串"和“字符串"类型的操作数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!