Suppose there is an N-th number of directories, each directory stores M files with unique names that do not overlap with files from other directories.

How efficient is it to put everything in the dictionary, so that by the name of the file I could get the directory where it lies, and the key + values ​​= path to the file?

The solution to the forehead is to duplicate the path for each key, but then it turns out that the path to the same directory will be duplicated several times, which consumes RAM.

  • 1) Get a list of all directories. 2) For each directory, get a list of files and enter into the dictionary, specify the directory as a value, the file name as a key. - tym32167
  • Yes, but it turns out that 10 files from one directory will refer to 10 lines, and this is a waste of memory. - iluxa1810
  • 10 files will link to the same line if they are in the same directory - tym32167
  • Yes, but the memory will be 10 lines per 10 files, and not 1 single line. - iluxa1810
  • 3
    Memory will be 1 line and 10 references to it - tym32167

1 answer 1

As an example:

var root = @"C:\.....root_dir"; var dictionary = new Dictionary<string, string>(); var directories = Directory.GetDirectories(root); foreach (var d in directories) { var files = Directory.GetFiles(d).Select(x => Path.GetFileName(x)); foreach (var f in files) { dictionary.Add(f, d); } } 

As you can see, the directory added for neighboring files is the same. That is, for 10 neighboring files there will be a link to the same directory.

  • Yes, I now checked through Object.ReferenceEquals and the string for one key is equal to the string for the other => I was wrong. - iluxa1810
  • @ iluxa1810 is an option easier Console.WriteLine(typeof(string).IsValueType); - tym32167