Search code examples
vb.netlinq

VB.NET - Can I use LINQ over a List(of String) to find strings that end with items from another List(of String)?


I have a List(of String) with some names in them. I have another List(of String) that has suffixes in them, and I was hoping I could use LINQ to pull a list of the names that end with any of the suffixes in that list.

I can do it programmatically using a pair of nested FOR..EACH loops but was wanted to find a cleaner way using LINQ.

I've tried a few different approaches with .Any and .Contains without success.


Solution

  • You can use Where and String.EndsWith in Any:

    Dim matchingNames = names.
        Where(Function(name) suffixes.Any(Function(suffix) name.EndsWith(suffix)))
    

    If you want to compare in a case insensitive manner, use the overload of EndsWith.