简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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