Search code examples
c#stringstartswith

string.StartsWith element from the list


Here is my code:

private bool isSpecialZone(string zoneNumber, string clientName)
{
    var notSpecialZones = new List<string> { "200", "201", "202" };
    return clientName.Contains("XXX") && !zoneNumber.StartsWith("200") && !zoneNumber.StartsWith("201") && !zoneNumber.StartsWith("202");
}

I would like to make it cleaner and instead of repeating the "StartsWith" everywhere have one statement. Is there a way to do this?


Solution

  • This next linq statement does exactly what you want. As soon as it sees the zoneNumber starts with a 'notSpecialZone' it stops and returns. By supplying the '!' we reverse the result so it matches the method.

    private bool isSpecialZone(string zoneNumber, string clientName)
    {
        var notSpecialZones = new List<string> { "200", "201", "202" };
        return clientName.Contains("XXX") && !notSpecialZones.Any(zone => zoneNumber.StartsWith(zone)); 
    }