Sonhja
Sonhja

Reputation: 8458

How to check if a string is contained in another list of strings?

I have a list of folders in which I contain a list of languages that I want to be processed:

eng_US
spa_ES

etc...

I have a list of directories containing subfolders for each language it has. They can be more than the ones defined in my languages list. It can look like this:

ja-JP
eng_US
spa_Es
fr_FR

I list the directories in that specific folder like this:

string[] directories = Directory.GetDirectories(path);

I want to get with Linq all that folders that are inside my private language list.

I tried something similar to this:

string[] directories = Directory.GetDirectories(path).Where(x => x.Contains(languageList.Value));

But, obviously is bad :(

How can I get only the folders which are also listed in my private language list?

So, how can I check if my resulting path is contained inside another string list with Linq?

Thanks!

NOTE: My language list is saved in a Dictionary.

IDictionary<int, string> languages;

Upvotes: 1

Views: 197

Answers (2)

John Bustos
John Bustos

Reputation: 19574

You're pretty close - Remember languageList is a list of names you care about and your Linq statement will return one string value at a time to put through your Where clause, so you'd want it to look as follows:

string[] directories = Directory.GetDirectories(path).Where(x => languageList.Contains(x)).ToArray();

Basically saying Give me back and returned value that is contained in languageList

Hope that makes sense.

Upvotes: 1

TheLethalCoder
TheLethalCoder

Reputation: 6744

You need to compare on the directory name not the full path. Also you are checking if the directory path contains a value gotten from language list.

string[] directories = Directory.GetDirectories(path)
                                .Where(d => languageList.Contains(Path.GetFileName(d)))
                                .ToArray();

Note that you have to use Path.GetFileName as this will return 'endfolder' from 'C:\folder\endfolder'. Whereas Path.GetDirectoryName will return 'C:\folder'.

Upvotes: 0

Related Questions