I needed to test a string to see whether it ends with any of an array of strings.
I found the perfect solution using LINQ by following this answer:
string test = "foo+";
string[] operators = { "+", "-", "*", "/" };
bool result = operators.Any(x => test.EndsWith(x));
Now I want to get the string that matched and that's where I'm currently stuck with.
I tried adding at the end
text_field.Text = x;
and that errored out with a message about scope - and rightfully so, I was expecting that error. I also tried to declare a string variable named x
at the very top and another error came out of it - something about not being able to re-declare the variable in a different scope. I guess I'm used to PHP so much where you can re-declare a variable with no issues.
Your best bet is to do a FirstOrDefault
and then check if that is null/empty/etc as if it were your bool. Though this is a very basic example it should get the point across. What you do with that result and if it should just be one or more, etc is up to your circumstances.
static void Main()
{
string test = "foo+";
string[] operators = { "+", "-", "*", "/" };
bool result = operators.Any(x => test.EndsWith(x));
string actualResult = operators.FirstOrDefault(x => test.EndsWith(x));
if (result)
{
Console.WriteLine("Yay!");
}
if (!string.IsNullOrWhiteSpace(actualResult))
{
Console.WriteLine("Also Yay!");
}
}