Reputation:
I want to achieve the following functionality using LINQ.
Case 1:
listOfStrings = {"C:","D:","E:"}
myString = "C:\Files"
Output: True
Case 2:
listOfStrings = {"C:","D:","E:"}
myString = "F:\Files"
Output: False
Upvotes: 2
Views: 259
Reputation: 310852
Try this:
bool contains = listOfStrings.Exists(s => myString.IndexOf(s)!=-1);
If you know that it should be at the start of the string, then:
bool contains = listOfStrings.Exists(s => myString.StartsWith(s));
EDIT Marc's solution is nicer :)
Upvotes: 0
Reputation: 103740
You can use the Any extension method:
bool result = listOfStrings.Any(str => str.StartsWith(...));
Upvotes: 0
Reputation: 1062650
bool b = listOfStrings.Any(myString.StartsWith);
or slightly more verbose (but easier to understand):
bool b = listOfStrings.Any(s => myString.StartsWith(s));
Upvotes: 8