Two nice string extensions
Here’s a couple (well, one is an overload of the other) of string extension methods I wrote today which I’m quite fond of:
/// <summary>
/// Determines if any of the given matches are a case sensitive match for the
/// nominated string value
/// </summary>
/// <param name="text">The string value to be checked</param>
/// <param name="matches">The list of potential matches</param>
static public bool IsIn(this string text, params string[] matches)
{
return IsIn(text, true, matches);
}
/// <summary>
/// Determines if any of the given matches are a case sensitive match for the
/// nominated string value
/// </summary>
/// <param name="text">The string value to be checked</param>
/// <param name="caseSensitive"><c>true</c> to perform a case
/// sensitive match</param>
/// <param name="matches">The list of potential matches</param>
static public bool IsIn(this string text, bool caseSensitive, params string[] matches)
{
StringComparison comparer = caseSensitive
? StringComparison.CurrentCulture
: StringComparison.CurrentCultureIgnoreCase;
return matches.Any(value => text.Equals(value, comparer));
}
So instead of writing this:
if (name == "James" || name == "Peter" || name == "Sally")
Console.WriteLine("Your name is too generic!");
You can simply write this:
if (name.IsIn("James", "Peter", "Sally")
Console.WriteLine("Your name is too generic!");
No offence to the James, Peters, and Sallys of the world.
