C# lambda 表达式无法管理某个字符串比较
我有一个特定的 lambda ,尽管逻辑看起来很合理,但它似乎不想正常工作。
index = llCodeList.FindIndex(f => string.Compare(f.Threshold.ToString(), searchText, true ) >= 0);
f.Threshold 是一个整数值,似乎转换没有发生,它破坏了我的搜索功能。有人能解释一下吗?
I have a specific lambda what doesn't seem to want to work properly although the logic seems sound.
index = llCodeList.FindIndex(f => string.Compare(f.Threshold.ToString(), searchText, true ) >= 0);
f.Threshold is an integer value, it seems that the conversion doesn't happen and it breaks my search function. Can anyone shed some light on this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为什么不放弃字符串比较并显式检查?
您确定搜索文本是阈值数字的子集吗?
另外,您可能不了解
string.Compare
的工作原理,它不会检查数字值,而是检查字符串值。对于上述内容,如果searchText
为4
并且阈值为-40
将与您的谓词匹配。我的示例更明确地演示了string.Compare(...,...,...) >= 0
的行为,如果您尝试根据大于或等于阈值和搜索文本的匹配,你可以这样做
Why not ditch the string compare and explicitly check?
Are you sure that the search text is a subset of the threshold number?
Also it may be that you're not understanding how
string.Compare
works, it won't check numerical value but string value. For the above ifsearchText
is4
and the threshold is-40
would match your predicate. My example more explicitly demonstrates the behavior ofstring.Compare(...,...,...) >= 0
If you're trying to find results based on having a greater than or equal to match on threshold and searchText you could do this
如果我的评论正确地理解了您想要做的事情的要点,那么请执行以下操作:
If my comment correctly got the gist of what you are trying to do then do something like this:
我认为您的意思是检查
IndexOf
而不是使用Compare
。但名称
FindIndex
听起来像是您想要返回实际索引。我的水晶球说你正在寻找类似的东西I think you meant to check
IndexOf
instead of usingCompare
.But the name
FindIndex
sounds like you'd want to return the actual index. My crystal ball says you're looking for something like