Dictionaries/Maps are usually implemented on top of some sort of hashing system. This isn’t precisely required, but it allows extremely fast access by key. The disadvantage is that the data isn’t stored in any human-friendly order.

Cicely’s co-worker had a problem with this. They wanted to store key value pairs- specifically, the titles of a media item, and the actual object representing the media items. They wanted to be able to fetch items by their title, but they also wanted to be able to present the items sorted by their title.

As this was C#, there are a number of ways to handle that sorting as needed. But Cicely’s co-worker took a… different approach.

class MultimediaPackagerResult
{
  public class MediaItemWrapper
  {
    public string Title { get; }
    public List<MediaItem> Items { get; }

    public MediaItemWrapper(string title, List<MediaItem> items)
    {
      Title = title;
      Items = items;
    }
  }
  private readonly Dictionary<int, MediaItemWrapper> sortedItems;

  public MultimediaPackagerResult()
  {
    sortedItems = new Dictionary<int, MediaItemWrapper>();
  }

  public void AddRootItemWithSort(int index, string name, List<MediaItem> value)
  {
    sortedItems.Add(index, new MediaItemWrapper(name, value));
  }

  public Dictionary<string,object> GetResultsWithSort()
  {
    var sortedList = sortedItems.OrderBy(item => item.Key).Select(item => item.Value);
      
    return new Dictionary<string, object>
    {
      { "Sections", sortedList}
    };
  }
}

Creating a dictionary of types Dictionary<int, MediaItemWrapper> isn’t wrong per-se; you might want a sparse array and that’s a great way to implement one. But here, we’re inserting items at arbitrary positions, presumably in the order we want to retrieve them. The goal, I might repeat, is to sort them by their title.

So, to properly insert into this collection, you need to figure out what the correct index is, and insert the item there. Then, when you GetResultsWithSort, this code OrderBys the item.Key, the index you assigned each item, based on its title.

The worst part of this code is that the original developer clearly understood how to use OrderBy(item=>item.Key) to sort a dictionary. They just couldn’t connect the dots to how that works with titles.

Cicely deleted all of this code and replaced it with a more straightforward dictionary of MediaItem objects.

[Advertisement] Utilize BuildMaster to release your software with confidence, at the pace your business demands. Download today!