HashMap. Create entry (int, string[]) a push into value immediately
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 Reply
var files = dinfo.EnumerateFiles()
.Select(finfo => new { finfo.Name, finfo.Length })
.GroupBy(file => file.Length)
.ToDictionary(group => group.Key, group => group.Select(file => file.Name));
The solution so far