问题
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 as an extension method, for strings.
eg.
var collection = string[] { "ny", "er", "ty" };
"Johnny".EndsWith(collection); // returns true.
"Fred".EndsWith(collection); // returns false.
回答1:
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");
回答2:
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;
}
回答3:
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;
}
}
来源:https://stackoverflow.com/questions/1641499/how-can-i-use-linq-to-to-determine-if-this-string-endswith-a-value-from-a-colle