简体   繁体   中英

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.Contains('q')

but it gives me an error saying:

The best overloaded method match for 'string.Contains(string)' has some invalid arguments.

And it's write: string.Contains doesn't have an overload taking just a single character.

Options:

  • Use @ViewBag.Options.Contains("q")
  • Use @ViewBag.Options.IndexOf('q') != -1
  • Use some more complicated LINQy approach (eg Any ) - feasible, but there's no need here. (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)
  • 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.

Using single quotes in c# indicates a character.

Try with double quotes:

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

用这个:

@ViewBag.Options.Contains("q")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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