简体   繁体   English

如何与字符串数组和字符串进行比较

[英]How to compare with a string array and string

I want to compare one string with the string array because I need to match a phone number if it starts with some specific number then I need to do something. 我想将一个字符串与字符串数组进行比较,因为如果电话号码以某个特定的数字开头,那么我需要匹配一个电话号码,然后我需要执行一些操作。

Here is what I'm doing now. 这就是我现在正在做的。 But I want to make this simpler. 但我想简化一下。

string[] startNumList = new string[] {"4", "5", "6", "7", "8" };
foreach (string x in startNumList)
{
      if(request.ReferenceNumber.StartsWith(x))
       {
            //do something
       }
 }

I was jut wondering if this is possible to do the same with one line LINQ. 我当时想知道是否可以用一行LINQ做到这一点。 Thanks in advance. 提前致谢。

It's hard to give a definitive answer to this sort of question, but I'd go with this: 很难给出这类问题的明确答案,但我会同意:

var matchingStartNumber = startNumList.FirstOrDefault(x => request.ReferenceNumber.StartsWith(x));
if (matchingStartNumber != null)
{
    // Do stuff with startNum
}

If you want to avoid the foreach loop you can use "Any" method from Linq to see if any items in your "startNumList" match the condition. 如果要避免foreach循环,可以使用Linq中的“ Any”方法来查看“ startNumList”中的任何项目是否符合条件。

if(startNumList.Any(x => request.ReferenceNumber.StartsWith(x)))
{
                //do something
}

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

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