Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 as an extension method, for strings.

eg.

var collection = string[] { "ny", "er", "ty" };
"Johnny".EndsWith(collection); // returns true.
"Fred".EndsWith(collection); // returns false.
like image 487
Pure.Krome Avatar asked Oct 29 '09 03:10

Pure.Krome


People also ask

How do you use LINQ to check if a list of strings contains any string in a list?

Select(x => new { x, count = x. tags. Count(tag => list. Contains(tag)) }) .

Can you use LINQ on a string?

LINQ can be used to query and transform strings and collections of strings. It can be especially useful with semi-structured data in text files. LINQ queries can be combined with traditional string functions and regular expressions. For example, you can use the String.

How to use EndsWith in C#?

In C#, EndsWith() is a string method. This method is used to check whether the ending of the current string instance matches with a specified string or not. If it matches, then it returns the string otherwise false. Using “foreach” loop, it is possible to check many strings.

How to use contains in LINQ in C#?

The Linq Contains Method in C# is used to check whether a sequence or collection (i.e. data source) contains a specified element or not. If the data source contains the specified element, then it returns true else return false.


1 Answers

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");
like image 107
Pierre-Alain Vigeant Avatar answered Nov 02 '22 01:11

Pierre-Alain Vigeant