Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a string is doesn't equal all of these?

Trying to rewrite this using LINQ:

if (mode != "A" && mode != "B" && mode != "C" && mode != "D" && mode != "E" && mode != "F" && mode != "G")
{
   continue;
}

What would be the most clear and concise way to refactor this? I could have sworn I'd seen a post like this before but I cannot find it at the moment.

like image 481
Ryan Peschel Avatar asked Dec 07 '22 11:12

Ryan Peschel


2 Answers

You can use Contains method from IList<T>:

IList<string> modes = new[]{"A","B","C","D","E","F","G"};
if (!modes.Contains(mode))...
like image 118
Sergey Kalinichenko Avatar answered Dec 08 '22 23:12

Sergey Kalinichenko


Write an extension method for the string class

public static bool In(this string s, params string[] values)
{
    return values.Any(x => x.Equals(s));
}

call it in this way

if (!mode.In("A", "B", "C", "D","E","F", "G")
{
    continue;
}
like image 32
Steve Avatar answered Dec 09 '22 00:12

Steve