TheLameProgrammer
TheLameProgrammer

Reputation:

To determine if one of the Strings from a list contains the initial part of a specified string using LINQ

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

Answers (3)

Drew Noakes
Drew Noakes

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

BFree
BFree

Reputation: 103740

You can use the Any extension method:

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

Upvotes: 0

Marc Gravell
Marc Gravell

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

Related Questions