有没有一种方法可以评估 string.contains() 方法内的多个字符串?
if (description.ToUpper().Contains("BOUGHT") || description.ToUpper().Contains("PURCHASE"))
上面的代码是我所拥有的,我想知道对于相同的条件是否有更长的字符串列表,我将如何在不使代码太长的情况下做到这一点。也许是 lambda 表达式?
if (description.ToUpper().Contains("BOUGHT") || description.ToUpper().Contains("PURCHASE"))
The code above is what I have and I wondered if I had a longer list of strings for the same condition, how I would do it without making the code too long. Maybe a lambda expression?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
不,没有内置功能。不过自己写也不难:
我只将
hackstack
转换为upper一次,以提高性能。或者,您可以使用
IndexOf(needle, StringComparison.OrdinalIgnoreCase)>=0
:您不应在此处使用
ToUpper()
,因为它使用当前区域性。在某些计算机上使用当前区域性可能会导致意外问题,例如,使用土耳其区域性时,i
不会大写为I
。两侧的
ToUpperInvariant()
可能仍然存在一些微妙的问题,并且不区分大小写的比较可能会返回不同的结果,但只有当您的干草堆和针中都有不寻常的字符时,这才有意义。No, there is no built in function. But it's not hard to write it yourself:
I only convert
hackstack
to upper once to improve performance.Alternatively you could use
IndexOf(needle, StringComparison.OrdinalIgnoreCase)>=0
:You should not use
ToUpper()
here, since that uses the current culture. Using the current culture can lead to unexpected problems on some computers, for examplei
does not uppercase toI
when using the Turkish culture.There might still some subtle problems remaining where
ToUpperInvariant()
on both sides and a case insensitive comparison might return different results, but that's only relevant if you have unusual characters in both your haystack and needles.您可以将代码修改为如下所示:
You can rework the code to something like this:
使用正则表达式:
Use a regular expression:
如果字符串包含正则表达式控制字符,您可能必须对它们进行转义。
You might have to escape the strings if they contain Regex control characters.