String.EndsWithAny and StartsWithAny Extension Method

It frustrated me that while String provides the StartsWith and EndWith method, it doesn’t provide an EndWithAny. So, if I wanted to see if a particular string started or ended with any specified string, I would have to create my own method to return a true or false.
Whilst this is fine, it’s a little clunky if I want to use it in various places in my application.

For this reason, I decided to create an extension method:


public static bool EndsWithAny(this string input, params char[] endings)
	foreach (var x in endings)
		if (input.EndsWith(x.ToString()))
			return true;

	return false;

The method is very similar for StartsWithAny:

public static bool StartsWithAny(this string input, params char[] beginnings)
	foreach (var x in beginnings)
		if (input.StartsWith(x.ToString()))
			return true;

	return false;

I’ll write up a post on Extension Methods as soon as I get a chance.

For now, the MSDN one may help….

2 responses to “String.EndsWithAny and StartsWithAny Extension Method”

  1. DotNetWise avatar

    Why do you do x.ToString() for each element?
    That sucks, performance wise!

    1. Alex avatar

      Feel free to improve it, constructively.

Leave a Reply

Your email address will not be published. Required fields are marked *