HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpModerate

Determining whether a string ends with one of a few given options

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
determiningwithgivenoptionsendsonefewwhetherstring

Problem

I wrote the following function to determine whether a string ends with one of a few given options.

I'm sure it can be written more elegantly, probably avoiding the loop.

bool EndsWithOneOf(string value, IEnumerable suffixes)
{ 
    foreach(var suffix in suffixes)
    {
        if value.EndsWith(suffix)
            return true;
    }
    return false;
}

Solution

You can LINQify it to improve readability:

bool endsWithOneOf = suffixes.Any(x => value.EndsWith(x));


Note that this doesn't "avoid the loop", since Any() will iterate through the suffixes (stopping when it hits a match.) But that's ok, since how else could you do it? You have an enumeration of suffixes, so to do anything with them, you must enumerate them.

Code Snippets

bool endsWithOneOf = suffixes.Any(x => value.EndsWith(x));

Context

StackExchange Code Review Q#4200, answer score: 15

Revisions (0)

No revisions yet.