Коллекция с доступом по индексу и с сортировкой - C#
Формулировка задачи:
Добрый вечер. У меня возникла одна задача для решения которой мне нужна некая коллекция <key,value>, которая позволяет считывать\записывать значения по индексу и сортироваться по значению. Наиболее подходящая это Dictinary, но она не умеет сортировать по значению, и доступа по индексу нет.
Решение задачи: «Коллекция с доступом по индексу и с сортировкой»
textual
Листинг программы
static class Program
{
private static void Main(string[] args)
{
MyDictionary<string,int> numbers = new MyDictionary<string, int>();
numbers.Add("three",3);
numbers.Add("two",2);
numbers.Add("one",1);
foreach (var e in numbers.OrderByValue())
{
Console.WriteLine(e.Key);
}
Console.WriteLine(numbers.GetValue(1));
Console.ReadKey();
}
}
public class MyDictionary<TKey,TValue> : Dictionary<TKey,TValue>
{
public MyDictionary<TKey,TValue> OrderByValue()
{
return (MyDictionary<TKey, TValue>) this.OrderBy(pair => pair.Value)
.ToDictionary(pair => pair.Key, pair => pair.Value);
}
public TValue GetValue(int index)
{
var enumerator = GetEnumerator();
for (int i = -1; i < index; i++)
if(!enumerator.MoveNext())
throw new IndexOutOfRangeException();
return enumerator.Current.Value;
}
}