在LINQ中获取与Any匹配的字符串

时间:2018-05-01 19:45:04

标签: c# arrays linq ends-with

我需要测试一个字符串,以查看它是否以任何字符串数组结束。

我按照this answer

找到了使用LINQ的完美解决方案
string test = "foo+";
string[] operators = { "+", "-", "*", "/" };
bool result = operators.Any(x => test.EndsWith(x));

现在我想获得匹配的字符串以及我目前所处的位置。

我尝试在最后添加

text_field.Text = x;

并且错误地显示了关于范围的消息 - 这是理所当然的,我期待这个错误。我还尝试在最顶层声明一个名为x的字符串变量,并且出现了另一个错误 - 无法在不同的范围内重新声明该变量。我想我已经习惯了PHP,你可以重新声明一个没有问题的变量。

3 个答案:

答案 0 :(得分:2)

我会使用正则表达式

string test = "foo+";
var match = Regex.Match(test, @".+([\+\-\*\\])$").Groups[1].Value;
如果字符串未以""

结尾,

匹配将为+-*/

答案 1 :(得分:0)

你最好的办法是做一个FirstOrDefault,然后检查是否为null / empty / etc,好像它是你的bool。虽然这是一个非常基本的例子,但它应该得到重点。你对这个结果做了什么,如果它只是一个或多个,等等取决于你的情况。

    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!");
        }
    }

答案 2 :(得分:0)

如果我理解正确,这将为您提供操作员

string test = "foo+";
string[] operators = { "+", "-", "*", "/" };
var result = operators.Where(x => test.EndsWith(x)) ;

这只会返回最后一个使用过的运算符,所以如果它以 - + *结尾,它将为你提供字符串中的最后一个字符

相关问题