HashMap. Create entry (int, string[]) and push into value immediately

Viewed 41

I want to get all files of the same size in buckets according, size is a key.

Default behaviour would override the value whenever you associate it with an existing key. I want to push a value to string[] array whenever the same value is met. 1556 - "1.txt" - Entry added to the dictionary, 1.txt put to the string[] 1556 - "7.txt" - 7.txt pushed to the string[] associated with 1556

My current thought is to enumerate once through all files and create entries with keys and empty arrays in the dictionary:

foreach(var file in directory){
map[file.length] = new string[]/List<string>();

then enumerate second time retrieving array associated with current key:

foreach(var file in directory){
map[file.length].push(file.name);
}

Are there any better ways to do this?

1 Answers

As far as I understood, you want entries to consist of fileSize as keys, fileNames array as value.

In that case, I'd suggest to use just one loop, like so:

foreach(var file in directory)
{
    if (!map.ContainsKey(file.Length)) 
    {
        map.Add(file.Length, new List<string>());
    }
    map[file.Length].Add(file.Name);
}

Edit: removed space for each file name.

Related