Check if a string contains an element from a list (of strings)

c#, coding-style, list, performance, vb.net

Solution

With LINQ, and using C# (I don't know VB much these days):

bool b = listOfStrings.Any(s=>myString.Contains(s));

or (shorter and more efficient, but arguably less clear):

bool b = listOfStrings.Any(myString.Contains);

If you were testing equality, it would be worth looking at `HashSet` etc, but this won't help with partial matches unless you split it into fragments and add an order of complexity.

update: if you really mean "StartsWith", then you could sort the list and place it into an array ; then use `Array.BinarySearch` to find each item - check by lookup to see if it is a full or partial match.

Update: in the recent .Net, Contains has optional StringComparison parameter , that can be used for case-insensitive comparison, e.g. myString.Contains(s,StringComparison.CurrentCultureIgnoreCase);

Problem

For the following block of code: ``` For I = 0 To listOfStrings.Count - 1 If myString.Contains(lstOfStrings.Item(I)) Then Return True End If Next Return False ``` The output is: Case 1: ``` myString: C:\Files\myfile.doc listOfString: C:\Files\, C:\Files2\ Result: True ``` Case 2: ``` myString: C:\Files3\myfile.doc listOfString: C:\Files\, C:\Files2\ Result: False ``` The list (listOfStrings) may contain several items (minimum 20) and it has to be checked against a thousands of strings (like myString). Is there a better (more efficient) way to write this code?

Original source

Related problems