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
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
bool b = listOfStrings.Any(myString.StartsWith);
or slightly more verbose (but easier to understand):
bool b = listOfStrings.Any(s => myString.StartsWith(s));
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 :)
You can use the Any extension method:
bool result = listOfStrings.Any(str => str.StartsWith(...));