How can I use Linq to to determine if this string EndsWith a value (from a collection)?

假如想象 提交于 2019-12-08 19:10:32

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!