如何使用Linq来确定此字符串Ends是否具有值(来自集合)?

Pur*_*ome 7 .net linq-to-objects

我试图找出一个字符串值是否EndsWith另一个字符串.这个"其他字符串"是集合中的值.我正在尝试将此作为字符串的扩展方法.

例如.

var collection = string[] { "ny", "er", "ty" };
"Johnny".EndsWith(collection); // returns true.
"Fred".EndsWith(collection); // returns false.
Run Code Online (Sandbox Code Playgroud)

Pie*_*ant 12

var collection = new string[] { "ny", "er", "ty" };

var doesEnd = collection.Any("Johnny".EndsWith);
var doesNotEnd = collection.Any("Fred".EndsWith);
Run Code Online (Sandbox Code Playgroud)

您可以创建一个String扩展来隐藏其使用 Any

public static bool EndsWith(this string value, params string[] values)
{
    return values.Any(value.EndsWith);
}

var isValid = "Johnny".EndsWith("ny", "er", "ty");
Run Code Online (Sandbox Code Playgroud)