Reputation: 297
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.
Upvotes: 1
Views: 113
Reputation: 271
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
}
Upvotes: 2
Reputation: 2912
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
}
Upvotes: 2