-Поиск по дневнику

Поиск сообщений в rss_thedaily_wtf

 -Подписка по e-mail

 

 -Постоянные читатели

 -Статистика

Статистика LiveInternet.ru: показано количество хитов и посетителей
Создан: 06.04.2008
Записей:
Комментариев:
Написано: 0


CodeSOD: Sorted by Title

Четверг, 06 Июня 2019 г. 09:30 + в цитатник

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 Items { get; }

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

  public MultimediaPackagerResult()
  {
    sortedItems = new Dictionary();
  }

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

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

Creating a dictionary of types Dictionary 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!

https://thedailywtf.com/articles/sorted-by-title

Метки:  

 

Добавить комментарий:
Текст комментария: смайлики

Проверка орфографии: (найти ошибки)

Прикрепить картинку:

 Переводить URL в ссылку
 Подписаться на комментарии
 Подписать картинку