Skip to content

Instantly share code, notes, and snippets.

@sunmeat
Created October 27, 2025 12:43
Show Gist options
  • Save sunmeat/ac401fdedc630f6565251cfeef703f93 to your computer and use it in GitHub Desktop.
Save sunmeat/ac401fdedc630f6565251cfeef703f93 to your computer and use it in GitHub Desktop.
non-generic collections C#
using System.Collections;
using System.Text;
class Program
{
static void Main()
{
Console.OutputEncoding = Encoding.UTF8;
ArrayListDemo();
HashtableDemo();
SortedListDemo();
StackDemo();
QueueDemo();
BitArrayDemo();
}
static void ArrayListDemo()
{
var al = new ArrayList();
Console.WriteLine(al.Capacity); // 0
al.Add("1");
Console.WriteLine(al.Capacity); // 4
al.Add("2");
al.Add("3");
al.Add(4);
al.Add(5);
Console.WriteLine(al.Capacity); // 8
al.AddRange(new int[] { 1, 2, 3, 4, 5 });
Console.WriteLine(al.Capacity); // 16
Console.WriteLine(al.Count); // 10
al.TrimToSize();
Console.WriteLine(al.Capacity); // 10
int a = Convert.ToInt32(al[0]);
Console.WriteLine(a);
Console.WriteLine(al[5] + "\n");
al.Clear();
float[] fl = { 2.3f, 6.3f, 7.1f, 6.2f, 3.4f };
al.AddRange(fl);
// сортування float через object з компаратором
IComparer comparer = Comparer<float>.Default;
al.Sort(comparer);
foreach (var item in al)
Console.Write(item + " ~ ");
Console.WriteLine("\n");
al.Clear();
al.Insert(0, "лисиця");
al.Insert(1, "чорна");
al.Insert(2, "стрибає");
al.Insert(3, "через");
al.Insert(4, "ріку");
al.Insert(5, "широку");
al.RemoveRange(0, 3);
al.Reverse();
foreach (var item in al)
Console.Write(item + ", ");
Console.WriteLine("\n");
// дні тижня
var week = new ArrayList(new string[] { "Понеділок", "Вівторок", "Середа", "Четвер", "П'ятниця", "Субота", "Неділя" });
var workweek = new ArrayList();
workweek.AddRange((ICollection)week.GetRange(0, 5));
foreach (string day in workweek)
Console.WriteLine(day);
((ArrayList)week).Sort();
Console.WriteLine();
foreach (string day in week)
Console.WriteLine(day);
Console.WriteLine();
// робота з файлами в директорії
var di = new DirectoryInfo(@"C:\1\");
var images = new ArrayList();
var files = di.GetFiles("*.mdf");
if (files.Length > 0)
{
images.AddRange(files);
Console.WriteLine("У цій директорії є такі файли:");
for (int i = 0; i < images.Count; i++)
{
FileInfo? file = (FileInfo?)images[i];
Console.WriteLine("Ім'я файлу: {0}", file?.Name);
}
}
Console.WriteLine();
}
static void HashtableDemo()
{
// хеш-таблиця зберігає пари ключ-значення з хешуванням для швидкого доступу
/* Клас Hashtable призначений для створення колекції, в якій
* для зберігання її елементів служить хеш-таблиця. Інформація
* зберігається в хеш-таблиці за допомогою механізму, званого
* хешування. При хешуванні для визначення унікального
* значення, званого хеш-кодом, використовується інформаційний
* вміст спеціального ключа. Отриманий у результаті хеш-код
* служить як індекс, за яким у таблиці
* зберігаються дані, що відповідають заданому ключу.
* Перетворення ключа на хеш-код виконується автоматично,
* і тому сам хеш-код взагалі недоступний користувачеві.
* Перевага хешування полягає в тому, що воно забезпечує
* сталість часу виконання операцій пошуку, вилучення та
* налаштування значень незалежно від величини масиву даних. */
var openWith = new Hashtable();
openWith.Add("txt", "notepad.exe");
openWith.Add("bmp", "mspaint.exe");
openWith.Add("jpg", "mspaint.exe");
openWith.Add("docx", "msword.exe");
try
{
openWith.Add("txt", "winword.exe"); // ключ уже існує, викине виняток
}
catch
{
Console.WriteLine("елемент з таким ключем уже існує\n");
}
Console.WriteLine("для ключа \"docx\", значення є " + openWith["docx"]);
openWith["docx"] = "wps.exe"; // змінюємо значення
Console.WriteLine("для ключа \"docx\", значення є " + openWith["docx"]);
openWith["rtf"] = "msword.exe"; // створюємо новий ключ
if (!openWith.ContainsKey("mp"))
{
openWith["mp3"] = "winamp.exe";
Console.WriteLine("для ключа \"mp3\", значення є " + openWith["mp3"]);
}
Console.WriteLine();
foreach (DictionaryEntry de in openWith)
Console.WriteLine("ключ: {0}, значення: {1}", de.Key, de.Value);
Console.WriteLine();
ICollection valueColl = openWith.Values;
foreach (string s in valueColl)
Console.WriteLine("значення = " + s);
Console.WriteLine();
ICollection keys = openWith.Keys;
foreach (string k in keys)
Console.WriteLine("ключ = " + k);
openWith.Remove("doc");
Console.WriteLine();
if (!openWith.ContainsKey("doc"))
Console.WriteLine("ключ \"doc\" не знайдено.");
Console.WriteLine();
}
static void SortedListDemo()
{
// відсортований список, сортує за ключами
var sl = new SortedList();
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("----------------------------");
IList keyList = sl.GetKeyList();
foreach (string name in keyList)
Console.WriteLine(name);
Console.WriteLine("----------------------------");
IList valueList = sl.GetValueList();
foreach (int age in valueList)
Console.WriteLine(age);
Console.WriteLine("----------------------------");
for (int i = 0; i < sl.Count; i++)
Console.WriteLine(sl.GetKey(i) + " " + sl.GetByIndex(i));
for (int i = sl.Count; i < 40; i++)
{
sl.Add(i.ToString(), i);
Console.WriteLine((i + 1) + " елемент - capacity: " + sl.Capacity);
}
Console.WriteLine();
}
static void StackDemo()
{
// стек, принцип lilo (last in - last out)
var st = new Stack();
st.Push(100);
st.Push(200);
st.Push(300);
foreach (int i in st)
Console.WriteLine(i);
Console.WriteLine("-------");
st.Pop();
foreach (int i in st)
Console.WriteLine(i);
Console.WriteLine("-------");
int last = (int)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();
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();
}
static void BitArrayDemo()
{
// масив бітів, змінний розмір для множини бітів
var bits1 = new BitArray(10);
bits1.SetAll(false);
bits1.Set(2, true);
bits1[3] = true;
bits1[8] = true;
var bits2 = (BitArray)bits1.Clone();
bits1.Not();
Console.Write("bits1: ");
Print(bits1);
Console.Write("bits2: ");
Print(bits2);
var notBits1 = (BitArray)bits1.Clone();
notBits1.Not();
Console.Write("NOT(bits1): ");
Print(notBits1);
var andRes = (BitArray)bits1.Clone();
andRes.And(bits2);
Console.Write("bits1 AND bits2: ");
Print(andRes);
}
static void Print(BitArray bits)
{
foreach (bool b in bits)
Console.Write(b ? 1 : 0);
Console.WriteLine();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment