How can I use Linq to to determine if this string EndsWith a value (from a collection)?
i'm trying to find out if a string value EndsWith
another string. This 'other string' are the values from a collection. I'm trying to do this 开发者_StackOverflow社区as an extension method, for strings.
eg.
var collection = string[] { "ny", "er", "ty" };
"Johnny".EndsWith(collection); // returns true.
"Fred".EndsWith(collection); // returns false.
var collection = new string[] { "ny", "er", "ty" };
var doesEnd = collection.Any("Johnny".EndsWith);
var doesNotEnd = collection.Any("Fred".EndsWith);
You can create a String extension to hide the usage of Any
public static bool EndsWith(this string value, params string[] values)
{
return values.Any(value.EndsWith);
}
var isValid = "Johnny".EndsWith("ny", "er", "ty");
There is nothing built in to the .NET framework but here is an extension method that will do the trick:
public static Boolean EndsWith(this String source, IEnumerable<String> suffixes)
{
if (String.IsNullOrEmpty(source)) return false;
if (suffixes == null) return false;
foreach (String suffix in suffixes)
if (source.EndsWith(suffix))
return true;
return false;
}
public static class Ex{
public static bool EndsWith(this string item, IEnumerable<string> list){
foreach(string s in list) {
if(item.EndsWith(s) return true;
}
return false;
}
}
精彩评论