开发者

.NET Collection needed to store file paths and extensions

开发者 https://www.devze.com 2023-02-11 20:01 出处:网络
I have a huge amount of file paths and file extensions to deal with : Each fil开发者_如何转开发e path has exactly one file extension associated with it.

I have a huge amount of file paths and file extensions to deal with :

  • Each fil开发者_如何转开发e path has exactly one file extension associated with it.
  • Each file extensions has one or more file paths associated with it.
  • Paths are unique, extensions aren't.

My goal is to easily retrieve all the file paths associated with a given file extension.

For example, if I ask "mp3", I'd like to know all the paths of the files with that extension.

Now, my question is : Which C# collection should I use to optimally do this and how should I use that collection?


I would use a Dictionary<string, List<string>> where the key would be the extension (for example, "mp3") which would return the list of file paths of type .mp3.

If you can use LINQ, you could use a single List<string> and retrieve file paths associated with a specific file extension like this:

List<string> s = new List<string>();
s.Add("c:\\documents and settings\\sound1.mp3");
s.Add("c:\\documents and settings\\sound2.mp3");
s.Add("c:\\documents and settings\\sound3.mp3");
s.Add("c:\\documents and settings\\something1.wav");
s.Add("c:\\documents and settings\\something2.exe");
s.Add("c:\\documents and settings\\abc.MP3");

var mp3paths = s.Where(x => String.Compare(".mp3", Path.GetExtension(x), true) == 0);
var exepaths = s.Where(x => String.Compare(".exe", Path.GetExtension(x), true) == 0);


If you're simply looking for a container to hold all of your extension and file path relationships, I'd suggest a Dictionary (specifically a Dictionary<string, List<string>>).

That way you can store a list of strings (i.e. a list of file paths) per file extension.

var dictionary = new Dictionary<string, List<string>>();
dictionary.Add("exe", new List<string>());
dictionary["exe"].Add("C:\Test\MyApp.exe");
dictionary["exe"].Add("C:\Test\AnotherApp.exe");
//Etc...

I hope this helps!


An alternative to the Dictionary already mentioned is a Lookup if the collection only needs to be set once and you want it to be immutable:

var myLookup = new DirectoryInfo(@"D:\samples").GetFiles()
                   .ToLookup(f => f.Extension);
var videoFiles = myLookup[".wmv"].ToList();
0

精彩评论

暂无评论...
验证码 换一张
取 消