CSharp · Console
using System;
using System.Collections.Generic;
struct MyDictionary
{
List<KeyValuePair<int, string>> list;
public int Length
{
get { return list.Count; }
private set { Length = value; }
}
public MyDictionary(int capacity = 0)
{
list = new List<KeyValuePair<int, string>>(capacity);
}
// Добавление элемента по ключу
public void Add(KeyValuePair<int, string> kvp)
{
for (int i = 0; i < list.Count; i++)
{
if (list[i].Key == kvp.Key)
{
Console.WriteLine("Такой ключ уже существует, добавление невозможно");
return;
}
}
list.Add(kvp);
}
// Удаление элемента по ключу
public void Remove(int key)
{
for (int i = 0; i < list.Count; i++)
{
if (list[i].Key == key)
{
Move(i);
return;
}
}
Console.WriteLine("Удаление не произошло");
}
// Смещение последующих элементов после удаления элемента наверх
void Move(int index)
{
int i;
for (i = index; i < list.Count - 1; i++)
list[i] = list[i + 1];
list.RemoveAt(i);
}
// Поиск значения по ключу
public string Search(int key)
{
for (int i = 0; i < list.Count; i++)
{
if (list[i].Key == key)
return list[i].Value;
}
return null; // ничего не найдено
}
}
class Program
{
static void Main()
{
MyDictionary dictionary = new MyDictionary(10);
KeyValuePair<int, string> kvpOne= new KeyValuePair<int, string>(1, "один");
dictionary.Add(kvpOne);
dictionary.Add(new KeyValuePair<int, string>(2, "два"));
dictionary.Add(new KeyValuePair<int, string>(3, "три"));
dictionary.Add(new KeyValuePair<int, string>(3, "три")); // не будет добавлено
for (int i = 0; i < dictionary.Length; i++)
Console.WriteLine(dictionary.Search(i + 1));
dictionary.Remove(4); // не будет удален
dictionary.Remove(2);
Console.WriteLine(dictionary.Search(1));
Console.WriteLine(dictionary.Search(3));
Console.ReadKey();
}
}