views:

124

answers:

3

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
+8  A: 
bool b = listOfStrings.Any(myString.StartsWith);

or slightly more verbose (but easier to understand):

bool b = listOfStrings.Any(s => myString.StartsWith(s));
Marc Gravell
Hey Marc, how did you change your answer without having an 'edit' show up?
Drew Noakes
I think it depends on a few factors: time; votes; comments - I haven't figured out the exact rules.
Marc Gravell
A: 

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 :)

Drew Noakes
A: 

You can use the Any extension method:

bool result = listOfStrings.Any(str => str.StartsWith(...));
BFree