简体   繁体   English

使用.Contains检查字符串是否包含字符时出错

[英]Error when using .Contains to check if a string contains a character

I am trying to find out if a string contains a character. 我试图找出一个字符串是否包含一个字符。 I tried the following where ViewBag.Options is a string: 我尝试了以下ViewBag.Options是一个字符串:

@ViewBag.Options.Contains('q')

but it gives me an error saying: 但它给了我一个错误说:

The best overloaded method match for 'string.Contains(string)' has some invalid arguments. 'string.Contains(string)'的最佳重载方法匹配有一些无效的参数。

And it's write: string.Contains doesn't have an overload taking just a single character. 而且它是写的: string.Contains只有一个字符没有重载。

Options: 选项:

  • Use @ViewBag.Options.Contains("q") 使用@ViewBag.Options.Contains("q")
  • Use @ViewBag.Options.IndexOf('q') != -1 使用@ViewBag.Options.IndexOf('q') != -1
  • Use some more complicated LINQy approach (eg Any ) - feasible, but there's no need here. 使用一些更复杂的LINQy方法(例如Any ) - 可行,但这里没有必要。 (I'm a fan of LINQ where appropriate but I don't think that's the right approach here; I wouldn't start introducing lambda expressions into my code just for the sake of it) (我在适当的时候是LINQ的粉丝,但我不认为这是正确的方法;我不会为了它而开始在我的代码中引入lambda表达式)
  • Use some more complicated regular expression approach - again, there's no point. 使用一些更复杂的正则表达式方法 - 再次,没有意义。

Use any of them 使用其中任何一个

  • @ViewBag.Options.Contains("q");
  • @ViewBag.Options.Any(x => x == 'q');

If you insist 如果你坚持

  • @ViewBag.Options.Contains('q'.ToString());

The error is self explanatory. 错误是自我解释的。 Paramerters of .Contains takes a string and no overload of this method takes a character. .Contains的.Contains接受一个字符串,此方法没有重载需要一个字符。

Using single quotes in c# indicates a character. 在c#中使用单引号表示一个字符。

Try with double quotes: 试试双引号:

@ViewBag.Options.Contains("q");

用这个:

@ViewBag.Options.Contains("q")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM