When you want to keep track of a group of objects in C#, you can do so by either creating arrays of objects or collections of objects. Collections offer a more flexible way of storing and referencing groups of objects compared to the fixed size and data type of arrays. The following is a brief overview of a few of the collections available in C# and their properties.
provides methods for searching, sorting, and modifying data
12345678910
List<int>numbers=newList<int>();numbers.Add(100);numbers.Add(101);numbers.Insert(0,99);// add 99 to start of Listforeach(intninnumbers){Console.WriteLine(n);// 99, 100, 101}
Queue
first in first out(FIFO)
1234567891011
Queue<int>numbers=newQueue<int>();numbers.Enqueue(5);numbers.Enqueue(6);numbers.Enqueue(7);while(numbers.Count>0){intn=numbers.Dequeue;// removes things from the queue during iterationConsole.WriteLine(n);// 5, 6, 7}
Stack
first in last out(LIFO)
1
Stack<int>numbers=newStack<int>();
Set
data structure that does not allow duplicates
1234567891011121314151617181920
varnumbers=newint[]{101,102,103,101,104};HashSet<int>seen=newHashSet<int>();foreach(intninnumbers){if(seen.Add(n)){Console.WriteLine($"{n} is new.");}else{Console.WriteLine($"Already saw {n}.");}}// 101 is new.// 102 is new.// 103 is new.// Already saw 101.// 104 is new.
Dictionary
all about key/value pairs
organized by key
not good for searching right to left(looking up names by phone numbers)
12345678
Dictionary<string,string>phoneNumbers=newDictionary<string,string>();phoneNumbers.Add("Dan","555-310-2345");phoneNumbers.Add("Joe","345-234-2340");phoneNumbers.Add("Johnny","123-432-9834");Console.WriteLine(phoneNumbers["Dan"]);// 555-310-2345Console.WriteLine(phoneNumbers["Steven"]);// throws an exception
ArrayList
do not use
lots of extra pointers
relatively slow
no specific size
stores everything as an object
defeats purpose of strong-typing
equivalent of a JavaScript array(undesirable in C#)
1234567
ArrayListarrList=newArrayList();arrList.Add(100);arrList.Add(101);arrList.Add("hello");intn=arrList[0];// Cannot implicitly convert type 'object' to 'int'intn=(int)arrList[0];// n = 100
HashTable
do not use
legacy
similar to ArrayList except key/value pairs instead of indexed