更全面、更灵活的解决方案,支持字符串比较:
using System;
using System.Collections.Generic;
using System.Linq;
public static class StringExtensions
{
public static bool EqualsAny(this string target, StringComparer comparer, params string[] values)
{
return target.EqualsAny(comparer, (IEnumerable<string>) values);
}
public static bool EqualsAny(this string target, params string[] values)
{
return target.EqualsAny((IEnumerable<string>)values);
}
public static bool EqualsAny(this string target, StringComparer comparer, IEnumerable<string> values)
{
return values.Contains(target, comparer);
}
public static bool EqualsAny(this string target, IEnumerable<string> values)
{
return values.Contains(target, StringComparer.OrdinalIgnoreCase);
}
}
用法:
if (title.EqualsAny("User greeting", "User name"))
{
//do stuff
}
PS重复@Servy的话:这样的解决方案适用于一小组值,对于大集合考虑使用Dictionary、HashSet等。