C# Collections – List, Dictionary, Query, Stack

Last Updated On Sunday 27th Mar 2022

List

Create a list of strings and Iterate through the list in CSharp

	using System.Collections.Generic;

// Create a list of strings.
var names = new List<string>();
names.Add("Adam");
names.Add("Alice");
names.Add("Kamal");
names.Add("Ben");

// Iterate through the list.
foreach (var name in names)
{
    Console.Write(name + " ");
}

// Output: Adam Alice Kamal Ben
	

Compare “same list” using Linq

Sort()‘s and destruction methods that because it is non-destructive in the OrderBy of Linq

	using System.Linq;
using System.Collections.Generic;

List<int> l1 = new List<int>() { 1, 2, 3 };
List<int> l2 = new List<int>() { 3, 1, 2 }; 

Enumerable.SequenceEqual(
  l1.OrderBy(n => n),
  l2.OrderBy(n => n)
); 
	

Dictionary

Create a new dictionary of strings with string keys and Add Some Elements to the dictionary.

	using System.Collections.Generic;

Dictionary<string, string> openWith = new Dictionary<string, string>();

// There are no duplicate keys, but some of the values are duplicates.
openWith.Add("txt", "notepad.exe");
openWith.Add("bmp", "paint.exe");
openWith.Add("dib", "paint.exe");
openWith.Add("rtf", "wordpad.exe");

Dictionary<string, object> user = new Dictionary<string, object>() {
  {"id", 1}, {"name", "john"}, {"age", 19}
};

Console.Write(user["name"]);
	

Queue

A queue can be enumerated without disturbing its contents.

First in, first out. The one you put in first is the one that is processed first.

	using System.Collections.Generic;

Queue<string> numbers = new Queue<string>();
numbers.Enqueue("one");
numbers.Enqueue("two");
numbers.Enqueue("three");
numbers.Enqueue("four");
numbers.Enqueue("five");

foreach( string number in numbers )
{
  Console.WriteLine(number);
}
	

Stack

A stack can be enumerated without disturbing its contents.

Last in, first out. The one that stack put in last is the one that is processed first.

	using System.Collections.Generic;

Stack<string> numbers = new Stack<string>();
numbers.Push("one");
numbers.Push("two");
numbers.Push("three");
numbers.Push("four");
numbers.Push("five");

foreach( string number in numbers )
{
  Console.WriteLine(number);
}
	

References

List

Dictionary

Queue

Stack