1

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. Thanks in advance.

10
  • 2
    Linq will actually loop the array in the same way you´re currently doing it. It only hides this away from you. Commented Dec 6, 2017 at 14:03
  • 1
    Why? LINQ would have to iterate the array as well. Commented Dec 6, 2017 at 14:03
  • 1
    LINQ and without looping is meaningless since Linq internally loops Commented Dec 6, 2017 at 14:03
  • If it loops internally I don't mind as I need to minimize the lines of code as well. Thanks Commented Dec 6, 2017 at 14:04
  • What is //do something? Commented Dec 6, 2017 at 14:04

2 Answers 2

2

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
}
Sign up to request clarification or add additional context in comments.

Comments

2

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.

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

2 Comments

The downside to this approach is if you need to know which value of 'x' matched within your logic, which is likely, then you've got to query again
@LordWilmore that’s true. This approach is only viable if it’s the same logic regardless of which number the phone number starts with.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.