Skip to content

Instantly share code, notes, and snippets.

@sunmeat
Created October 27, 2025 12:56
Show Gist options
  • Save sunmeat/ebf79aadcaea7ddb3085d0540812bb96 to your computer and use it in GitHub Desktop.
Save sunmeat/ebf79aadcaea7ddb3085d0540812bb96 to your computer and use it in GitHub Desktop.
generic collections C#
using System.Collections.Generic;
using System.Linq;
using System.Text;
class Program
{
static void Main()
{
Console.OutputEncoding = Encoding.UTF8;
DictionaryDemo();
SortedDictionaryDemo();
HashSetDemo();
SortedSetDemo();
LinkedListDemo();
ListDemo();
SortedListDemo();
StackDemo();
QueueDemo();
}
static void DictionaryDemo()
{
// словник представляє колекцію ключів і значень, генеричний еквівалент hashtable
var openWith = new Dictionary<string, string>();
openWith.Add("txt", "notepad.exe");
openWith.Add("bmp", "paint.exe");
openWith.Add("dib", "paint.exe");
openWith.Add("rtf", "wordpad.exe");
try
{
openWith.Add("txt", "winword.exe"); // ключ уже існує, викине виняток
}
catch
{
Console.WriteLine("елемент з таким ключем уже існує!\n");
}
Console.WriteLine("для ключа \"rtf\", значення є " + openWith["rtf"]);
openWith["rtf"] = "winword.exe"; // змінюємо значення за ключем
Console.WriteLine("для ключа \"rtf\", значення є " + openWith["rtf"]);
// якщо ключ не існував, створюється новий
openWith["doc"] = "winword.exe";
// trygetvalue ефективніше для частих перевірок ключів, яких немає
string? value = "";
if (openWith.TryGetValue("tif", out value))
{
Console.WriteLine("для ключа = \"tif\", значення = {0}.", value);
}
else
{
Console.WriteLine("ключ \"tif\" не знайдено.");
}
if (!openWith.ContainsKey("mp"))
{
openWith.Add("mp3", "winamp.exe");
Console.WriteLine("для ключа \"mp3\", значення є " + openWith["mp3"]);
}
Console.WriteLine();
foreach (KeyValuePair<string, string> kvp in openWith)
Console.WriteLine("ключ: {0}, значення: {1}", kvp.Key, kvp.Value);
Console.WriteLine();
foreach (string s in openWith.Values)
Console.WriteLine("значення = " + s);
Console.WriteLine();
foreach (string s in openWith.Keys)
Console.WriteLine("ключ = " + s);
openWith.Remove("doc");
Console.WriteLine();
if (!openWith.ContainsKey("doc"))
Console.WriteLine("ключ \"doc\" не знайдено.");
Console.WriteLine();
}
static void SortedDictionaryDemo()
{
// відсортований словник представляє пари ключ-значення, відсортовані за ключем
var openWith = new SortedDictionary<string, string>();
openWith.Add("txt", "notepad.exe");
openWith.Add("bmp", "paint.exe");
openWith.Add("dib", "paint.exe");
openWith.Add("rtf", "wordpad.exe");
try
{
openWith.Add("txt", "winword.exe"); // ключ уже існує, викинеться виняток
}
catch
{
Console.WriteLine("елемент з таким ключем уже існує!\n");
}
Console.WriteLine("для ключа \"rtf\", значення є " + openWith["rtf"]);
openWith["rtf"] = "winword.exe"; // змінюємо значення за ключем
Console.WriteLine("для ключа \"rtf\", значення є " + openWith["rtf"]);
// якщо ключ не існував, створюється новий
openWith["doc"] = "winword.exe";
// trygetvalue ефективніше для частих перевірок ключів, яких немає
string? value = "";
if (openWith.TryGetValue("tif", out value))
{
Console.WriteLine("для ключа = \"tif\", значення = {0}.", value);
}
else
{
Console.WriteLine("ключ \"tif\" не знайдено.");
}
if (!openWith.ContainsKey("mp"))
{
openWith.Add("mp3", "winamp.exe");
Console.WriteLine("для ключа \"mp3\", значення є " + openWith["mp3"]);
}
Console.WriteLine();
foreach (KeyValuePair<string, string> kvp in openWith)
Console.WriteLine("ключ: {0}, значення: {1}", kvp.Key, kvp.Value);
Console.WriteLine();
foreach (string s in openWith.Values)
Console.WriteLine("значення = " + s);
Console.WriteLine();
foreach (string s in openWith.Keys)
Console.WriteLine("ключ = " + s);
openWith.Remove("doc");
Console.WriteLine();
if (!openWith.ContainsKey("doc"))
Console.WriteLine("ключ \"doc\" не знайдено.");
Console.WriteLine();
}
static void HashSetDemo()
{
// hashset видаляє дублікати з масиву, унікальні елементи
string[] array1 = { "кішка", "собака", "кішка", "леопард", "тигр", "кішка" };
Console.WriteLine(string.Join(", ", array1));
var animals = new HashSet<string>(array1);
string[] array2 = animals.ToArray();
Console.WriteLine(string.Join(", ", array2));
int[] ar1 = { 1, 2, 3 };
int[] ar2 = { 3, 4, 5 };
int[] ar3 = { 9, 10, 11 };
var hs = new HashSet<int>(ar1);
bool a = hs.Overlaps(ar2);
bool b = hs.Overlaps(ar3);
Console.WriteLine("\n" + a); // true
Console.WriteLine(b + "\n"); // false
var countries = new HashSet<string> { "УКРАЇНА", "США", "АВСТРАЛІЯ", "КАНАДА", "КИТАЙ", "ФРАНЦІЯ" };
Console.WriteLine("містить Австралію: " + countries.Contains("АВСТРАЛІЯ"));
Console.WriteLine("містить Англію: " + countries.Contains("АНГЛІЯ") + "\n");
countries.Add("ІТАЛІЯ");
countries.Add("МЕКСИКА");
countries.Add("ІТАЛІЯ");
foreach (string coun in countries)
Console.WriteLine(coun);
countries.Remove("КАНАДА");
countries.RemoveWhere(c => c.Contains("США"));
Console.WriteLine();
foreach (string coun in countries)
Console.WriteLine(coun);
countries.UnionWith(animals);
Console.WriteLine();
foreach (string coun in countries)
Console.WriteLine(coun);
Console.WriteLine();
}
static void SortedSetDemo()
{
// відсортований набір, унікальні елементи в порядку
string[] array1 = { "кішка", "собака", "кішка", "леопард", "тигр", "кішка" };
var animals = new SortedSet<string>(array1);
Console.WriteLine(string.Join(", ", animals));
var countries = new SortedSet<string> { "УКРАЇНА", "США", "АВСТРАЛІЯ", "КАНАДА", "КИТАЙ", "ФРАНЦІЯ" };
countries.Add("ІТАЛІЯ");
countries.Add("МЕКСИКА");
countries.Add("ІТАЛІЯ");
Console.WriteLine("\n" + string.Join(", ", countries) + "\n");
}
static void LinkedListDemo()
{
// двозв'язний список для ефективних вставок/видалень
string[] words = { "лисиця", "стрибнула", "через", "собаку", "чорну", "велику" };
var sentence = new LinkedList<string>(words);
Display(sentence, "Значення двозв'язного списку:");
Console.WriteLine("sentence містить \"стрибнула\" = {0}",
sentence.Contains("стрибнула"));
// додаємо 'сьогодні' на початок
sentence.AddFirst("сьогодні");
Display(sentence, "Тест 1: Додаємо 'сьогодні' на початок списку:");
// переміщуємо перший вузол на кінець
LinkedListNode<string> mark1 = sentence.First;
sentence?.RemoveFirst();
sentence?.AddLast(mark1);
Display(sentence, "Тест 2: Переміщуємо перший вузол на останній:");
// змінюємо останній вузол на 'вчора'
sentence.RemoveLast();
sentence.AddLast("вчора");
Display(sentence, "Тест 3: Змінюємо останній вузол на 'вчора':");
// переміщуємо останній вузол на початок
mark1 = sentence.Last;
sentence.RemoveLast();
sentence.AddFirst(mark1);
Display(sentence, "Тест 4: Переміщуємо останній вузол на перший:");
// позначаємо останнє входження 'через' дужками
sentence.RemoveFirst();
LinkedListNode<string> current = sentence.FindLast("через");
IndicateNode(current, "Тест 5: Позначаємо останнє входження 'через':");
// додаємо 'лінива' та 'стара' після 'через' (вузол current)
sentence.AddAfter(current, "стара");
sentence.AddAfter(current, "лінива");
IndicateNode(current, "Тест 6: Додаємо 'лінива' та 'стара' після 'через':");
// позначаємо вузол 'лисиця'
current = sentence.Find("лисиця");
IndicateNode(current, "Тест 7: Позначаємо вузол 'лисиця':");
// додаємо 'швидка' та 'коричнева' перед 'лисиця'
sentence.AddBefore(current, "коричнева");
sentence.AddBefore(current, "швидка");
IndicateNode(current, "Тест 8: Додаємо 'швидка' та 'коричнева' перед 'лисиця':");
// зберігаємо посилання на current ('лисиця') та попередній вузол, позначаємо 'собаку'
mark1 = current;
LinkedListNode<string> mark2 = current.Previous;
current = sentence.Find("собаку");
IndicateNode(current, "Тест 9: Позначаємо вузол 'собаку':");
// addbefore викине invalidoperationexception, якщо вузол уже в списку
Console.WriteLine("Тест 10: Викидаємо виняток, додаючи вузол (лисиця), що вже в списку:");
try
{
sentence.AddBefore(current, mark1);
}
catch (InvalidOperationException ex)
{
Console.WriteLine("Повідомлення винятку: {0}", ex.Message);
}
Console.WriteLine();
// видаляємо вузол mark1 та додаємо перед current
sentence.Remove(mark1);
sentence.AddBefore(current, mark1);
IndicateNode(current, "Тест 11: Переміщуємо посилання на вузол (лисиця) перед поточним (собаку):");
// видаляємо поточний вузол
sentence.Remove(current);
IndicateNode(current, "Тест 12: Видаляємо поточний вузол (собаку) та намагаємося позначити:");
// додаємо видалений вузол після mark2
sentence.AddAfter(mark2, current);
IndicateNode(current, "Тест 13: Додаємо вузол, видалений у тесті 11, після посилання (коричнева):");
// remove знаходить та видаляє перший вузол з заданим значенням
sentence.Remove("стара");
Display(sentence, "Тест 14: Видаляємо вузол зі значенням 'стара':");
// при приведенні до iccollection<string>, add додає в кінець
sentence.RemoveLast();
ICollection<string> icoll = sentence;
icoll.Add("носоріг");
Display(sentence, "Тест 15: Видаляємо останній вузол, приводимо до iccollection та додаємо 'носоріг':");
Console.WriteLine("Тест 16: Копіюємо список у масив:");
string[] sArray = new string[sentence.Count];
sentence.CopyTo(sArray, 0);
foreach (string s in sArray)
{
Console.Write(s + ", ");
}
// очищуємо всі вузли
sentence.Clear();
Console.WriteLine();
Console.WriteLine("\nТест 17: Очищуємо двозв'язний список. Містить 'стрибнула' = {0}",
sentence.Contains("стрибнула"));
Console.WriteLine();
}
static void ListDemo()
{
// список представляє типізований список об'єктів з доступом за індексом, методи пошуку, сортування, маніпуляції
var dinosaurs = new List<string>();
Console.WriteLine("\nМісткість: {0}", dinosaurs.Capacity);
dinosaurs.Add("тиранозавр");
dinosaurs.Add("трицератопс");
dinosaurs.Add("стегозавр");
dinosaurs.Add("апатозавр");
dinosaurs.Add("анкилозавр");
Console.WriteLine();
foreach (string dinosaur in dinosaurs)
Console.WriteLine(dinosaur);
Console.WriteLine("\nМісткість: {0}", dinosaurs.Capacity);
Console.WriteLine("Кількість: {0}", dinosaurs.Count);
Console.WriteLine("\nМістить(\"тиранозавр\"): {0}",
dinosaurs.Contains("тиранозавр"));
Console.WriteLine("\nВставляємо(2, \"кархародонтозавр\")");
dinosaurs.Insert(2, "кархародонтозавр");
Console.WriteLine();
foreach (string dinosaur in dinosaurs)
Console.WriteLine(dinosaur);
// доступ за індексом через властивість item
Console.WriteLine("\ndinosaurs[3]: {0}", dinosaurs[3]);
Console.WriteLine("\nВидаляємо(\"кархародонтозавр\")");
dinosaurs.Remove("кархародонтозавр");
Console.WriteLine();
foreach (string dinosaur in dinosaurs)
Console.WriteLine(dinosaur);
dinosaurs.TrimExcess();
Console.WriteLine("\nTrimExcess()");
Console.WriteLine("Місткість: {0}", dinosaurs.Capacity);
Console.WriteLine("Кількість: {0}", dinosaurs.Count);
dinosaurs.Clear();
Console.WriteLine("\nClear()");
Console.WriteLine("Місткість: {0}", dinosaurs.Capacity);
Console.WriteLine("Кількість: {0}", dinosaurs.Count);
Console.WriteLine();
}
static void SortedListDemo()
{
// відсортований список, пари ключ-значення, відсортовані за ключем з IComparer<t>
var sl = new SortedList<string, int>();
Console.WriteLine(sl.Capacity);
sl.Add("Олександр", 1989);
Console.WriteLine(sl.Capacity);
sl.Add("Анастасія", 1991);
sl.Add("Микола", 1995);
sl.Add("Андрій", 1990);
sl.Add("Костянтин", 1993);
sl.Add("Марія", 1994);
Console.WriteLine("----------------------------");
foreach (var kvp in sl)
Console.WriteLine("ключ = {0}, значення = {1}", kvp.Key, kvp.Value);
Console.WriteLine("----------------------------");
Console.WriteLine();
foreach (int item in sl.Values)
Console.WriteLine("значення = {0}", item);
Console.WriteLine("----------------------------");
Console.WriteLine();
foreach (string s in sl.Keys)
{
Console.WriteLine("ключ = {0}", s);
}
Console.WriteLine();
}
static void StackDemo()
{
// стек, принцип LIFO (last in - first out), генеричний
var st = new Stack<int>();
st.Push(100);
st.Push(200);
st.Push(300);
foreach (var i in st)
Console.WriteLine(i);
Console.WriteLine("-------");
st.Pop();
foreach (var i in st)
Console.WriteLine(i);
Console.WriteLine("-------");
int last = st.Peek();
Console.WriteLine(last);
Console.WriteLine("-------");
Console.WriteLine(st.Contains(1));
Console.WriteLine(st.Contains(100));
Console.WriteLine("-------");
st.Clear();
Console.WriteLine(st.Count);
Console.WriteLine();
}
static void QueueDemo()
{
// черга, принцип FIFO (first in - first out), генеричний
var q = new Queue<int>();
for (int i = 1; i <= 5; i++)
{
q.Enqueue(i * 10);
Console.WriteLine(q.Dequeue());
}
Console.WriteLine("-----");
Console.WriteLine(q.Count);
Console.WriteLine("-----");
for (int i = 1; i <= 5; i++)
q.Enqueue(i * 10);
Console.WriteLine(q.Peek());
Console.WriteLine("-----");
foreach (int i in q)
Console.WriteLine(i);
Console.WriteLine();
}
private static void Display(LinkedList<string> words, string test)
{
Console.WriteLine(test);
foreach (string word in words)
{
Console.Write(word + " ");
}
Console.WriteLine();
Console.WriteLine();
}
private static void IndicateNode(LinkedListNode<string> node, string test)
{
Console.WriteLine(test);
if (node.List == null)
{
Console.WriteLine("Вузол '{0}' не в списку.\n",
node.Value);
return;
}
StringBuilder result = new StringBuilder("(" + node.Value + ")");
LinkedListNode<string> nodeP = node.Previous;
while (nodeP != null)
{
result.Insert(0, nodeP.Value + " ");
nodeP = nodeP.Previous;
}
node = node.Next;
while (node != null)
{
result.Append(" " + node.Value);
node = node.Next;
}
Console.WriteLine(result);
Console.WriteLine();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment