1

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;
Sonhja
  • 8,230
  • 20
  • 73
  • 131
  • 2
    "But, obviously is bad" — why do you think so? – Uwe Keim Jun 13 '16 at 14:39
  • Because it's not working and it's badly formatted. It doesn't even compile. I'm trying to use logic with Lynq, but not working... – Sonhja Jun 13 '16 at 14:42
  • Possible duplicate of [Does .NET have a way to check if List a contains all items in List b?](http://stackoverflow.com/questions/1520642/does-net-have-a-way-to-check-if-list-a-contains-all-items-in-list-b) – Thomas Ayoub Jun 13 '16 at 14:49
  • It looks like that, but don't understand how to apply it... I'm using .Net 4.5 – Sonhja Jun 13 '16 at 14:51
  • If you want to check (get a boolean result), there is a good answer below. However, if you want to get the intersection of two string lists, you should use exactly that: [Intersect](https://msdn.microsoft.com/en-us/library/bb460136(v=vs.100).aspx) – grek40 Jun 13 '16 at 15:02

2 Answers2

1

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.

John Bustos
  • 19,036
  • 17
  • 89
  • 151
0

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'.

TheLethalCoder
  • 6,668
  • 6
  • 34
  • 69