SF Developer
SF Developer

Reputation: 5384

List of strings - partial entry StartsWith using LINQ

Imagine I have this code

public List<string> X

and I load the following items:

launch.txt
reset.txt
foldername
otherfoldername

I know I can find if an item is on that list by calling X.Contains("value")
but what if I pass "foldername/file.txt".

What's the easiest way to check if a string starts with any of the entries on the X list? Ideally I want to catch all files that are inside "foldername/." and subdirectories too, so I thought to use the StartWith.

Is LINQ the right approach for this?

Upvotes: 0

Views: 1267

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460068

Use the Path class if you are fiddling around with paths:

List<string> X = new List<string>(){
    "launch.txt","reset.txt","foldername","otherfoldername"    
};
string search = "foldername/file.tx";
var searchInfo = new
{
    FileNameWoe = Path.GetFileNameWithoutExtension(search),
    FileName = Path.GetFileName(search),
    Directory = Path.GetDirectoryName(search)
};

IEnumerable<String> matches = X.Select(x => new
{
    str = x,
    FileNameWoe = Path.GetFileNameWithoutExtension(x),
    FileName = Path.GetFileName(x),
    Directory = Path.GetDirectoryName(x)
}).Where(xInfo => searchInfo.FileName    == xInfo.FileNameWoe
               || searchInfo.FileNameWoe == xInfo.FileName
               || searchInfo.Directory   == xInfo.Directory
               || searchInfo.Directory   == xInfo.FileNameWoe
               || searchInfo.FileNameWoe == xInfo.Directory)
.Select(xInfo => xInfo.str)
.ToList();

Finds: foldername because one of the filename's FileNameWithoutExtension equals the directory of the path you're searching.

Upvotes: 0

Timothy Shields
Timothy Shields

Reputation: 79441

Use the Enumerable.Any extension method, which returns true if and only if there is some item in the sequence for which the given predicate returns true.

string search = "foldername/file.txt";
bool result = X.Any(s => search.StartsWith(s));

Of course, StartsWith might not actually be appropriate for your scenario. What if there were only a folder named foldername2 in X? You wouldn't want result to be true in that case, I suspect.


If you want to get the items in X that match the search, you can do the following.

string search = "foldername/file.txt";
IEnumerable<string> result = X.Where(s => search.StartsWith(s));

If you want to get the first item in X that matches the search, you can do the following.

string search = "foldername/file.txt";
string result = X.FirstOrDefault(s => search.StartsWith(s));

Upvotes: 4

Related Questions