There are two genres of collection types in C#: that which is based off ICollection
(or IList
, which implements ICollection
), or that which is based off IDictionary
.
String
String are not collection types but the operations are quite similar. Really, a string can just be seen as a char array.
//String from and to char
letters = new char[]{'2','3','4','d',' ','~'};
var strFromChar = new string('c',3); //"ccc"
strFromChar = new string(letters);
strFromChar = new string(letters, 0, 3);
var charArr = strFromChar.ToCharArray();
var charAt1 = strFromChar[1];
Print(strFromChar.Length);
//Inspect strings
string str1 = "abcdeFG12";
str1.Contains('5'); //False
str1.IndexOf('d'); //4
str1.CompareTo("ab312FJ"); //1 , lexi compare
str1.StartsWith('b');
str1.EndsWith('2'); //True
Print(string.IsNullOrEmpty(str1));
//Insert, Remove, Replace, Slice
var str2 = str1.Insert(0,"A"); //Insert an A in front
str2 = str2.Remove(2); //Remove everything from index 2 to the end
str2 = str2.Replace('a','b'); //Replace all occurrences
var sub = str1.Substring(1,4); //Slice
//Join and Split
var str3 = string.Join(" ",
new string[]{str1,str2}); //Join two strings with sep
var strArr = str3.Split(
new char[]{' '}); //Split using separator
//Format
str2 = str2.ToLower();
str1 = str1.ToUpper();
str2 = str2.PadLeft(10); //str2 = " ab"
str2 = str2.Trim(); //str2 = "ab"
ICollection
Array
Don’t use ArrayList. Use array which supports generic type.
There are also this thing called multidimensional array int[,]
in contrast to our normal jagged array int[][]
. I am not sure yet how it is useful. Its performance is worse and it does not allow jagged list.
//Constructor
var arr = new int[5];
arr = new int[]{1,2,3};
Print(arr.Length);
var list = arr.ToList();
//Think Fill as "Replace"
Array.Fill(arr,3); //3,3,3
Array.Fill(arr,4,0,1); //4,3,3
//Clear, not Clean!; Must supply start and length argument
Array.Clear(arr,0,arr.Length);//0,0,0
arr = new int[]{3,2,3,4,5,3,7,8,3};
//Return the index of a value, if found
Print(arr.Contains(3));
Print(Array.BinarySearch(arr,3)); //2, the one closer to middle
Print(Array.IndexOf(arr,3)); //0, the first
Print(Array.LastIndexOf(arr,3)); //8, the last
//See if this array has such an element, and find its index
//You can also put in start and length constraint
//There is also FindLastIndex
Print(Array.Exists(arr, x => x > 10)); //False
Print(Array.FindIndex(arr, x => x > 5)); // 5
Print(Array.FindIndex(arr, 7, 1, x => x > 5)); // 7
//ForEach!
//The second argument is Action (must return void)
Array.ForEach(arr, x => x = x + 1);
//Resize
Array.Resize(ref arr, 5);//truncate
Array.Resize(ref arr, 10);//extra size filled with empty element
//Reverse
Array.Reverse(arr, 3, 6);//start, length
Array.Reverse(arr);
//Sort
Array.Sort(arr, 3, 6);//start, length
Array.Sort(arr);
var scores = new int[]{2,4,1,7,5};
var letters = new char[]{'A','B','C','D','E'};
Array.Sort(scores,letters);//letters becomes C A B E D
List
List can do what arrays can do, with some added functionality.
List is internally implemented with a self-expanding array.
//Basic operations
var li = new List<int>();
Print(li.Count);
li = new List<int>{-1,1,2,4,5,9};
li.Add(0);
li.AddRange(new int[]{4,2});
li.Insert(0,99);
li.RemoveAt(0);
li.Remove(9);
li.RemoveAll(x => x < 0);
li.RemoveRange(0,3);
li.Clear();
//List can do everything arrays can
li = new List<int>{1,2,3,4,5,0};
li.Contains(5);
li.IndexOf(5);
li.Exists(x => x < 0);
li.Reverse();
li.Sort();
//... and more
Stack, Queue
Queue<string> numbers = new Queue<string>();
numbers.Enqueue("one");
numbers.Enqueue("two");
var obj = numbers.Dequeue();
var top = numbers.Peek();
Print(numbers.Count);
Stack<string> myStack = new Stack<string>();
myStack.Push("Hello");
myStack.Push("World");
obj = myStack.Pop();
top = myStack.Peek();
Print(myStack.Count);
//You can iterate queue, stack with foreach
//You can use Contains with queue and stack
Like Dictionary, they also have methods like TryDequeue
/TryPeek
.
HashSet
IDictionary
Dictionary
Equivalent to a hashmap.
//Constructor
var dict = new Dictionary<string, int>();
arr = new int[]{0, 2, 4, 8, 12, 9};
dict = arr.ToDictionary(x=>x.ToString(), x=>x+1);
dict.Count();
var key = dict.Keys.ToList();
var value = dict.Values.ToList();
//Basic operations
dict.TryAdd("a",1);
dict.Add("z",2);
dict.ContainsKey("z");
dict.ContainsValue(1);
int val;
if(dict.TryGetValue("a",out val))
dict["a"] = val + 1;
dict.Remove("z");
dict.Clear();
//Iterate
foreach(KeyValuePair<string,int> kvp in dict){//just use var will do
//...do something
}
SortedList, SortedDictionary
Extension
LINQ Extension Methods
It works for all IEnumerable, we use a list as example.
import System.Linq;
var num = new List<int>(){2,5,8,1,4,2,9,0,-1};
var positive = num.Where(x => x > 0);
var stringify = num.Select(x => x + "+");
//we also have skip and take
var max = num.Max(x => x - 3); //Min, Average, Sum
var ord = num.OrderBy(x=>Math.Abs(x)).ThenByDescending(x=>x);
num.First();
num.FirstOrDefault();
num.Last();
num.LastOrDefault();
num.Prepend(1);
num.Append(2);
num.ElementAt(3);
var dis = num.Distinct(); //remove all repeat
var ecp = num.Except(new int[]{5,8});//Will remove all repeats too; Union, Intersect
Print(ecp.SequenceEqual(dis)); //Compare equality elementwise
Print(ecp.All(dis.Contains) && ecp.Count() == dis.Count()); //if all elements are the same (order not important)
Enumerable.Range(1,99); //start, length
Enumerable.Repeat("c",100);
Enumerable.Any(num,x=>x>0); //All
var collection = new int[4][];
var flattened = collection.SelectMany(x=>x);
Useful Extensions I wrote
namespace ExtensionMethods
{
using System;
using System.Collections.Generic;
public static class collectionExt
{
//Lazy way to print all elements in a list
public static void Show<T>(this ICollection<T> list){
foreach(T ele in list)
Console.Write("{0} ", ele);
Console.WriteLine();
}
//Lazy way to print all elements in a dict
public static void Show<T1,T2>(this IDictionary<T1,T2> list){
foreach(KeyValuePair<T1,T2> ele in list)
Console.Write("{0}:{1} ", ele.Key, ele.Value);
Console.WriteLine();
}
//Lazy way to do foreach iteration
public static void ForEach<T>(this IEnumerable<T> list, Action<T> f){
foreach (T ele in list)
f(ele);
}
}
}
- Post link: https://reimirno.github.io/2021/10/03/Common-CSharp-Collection-Type/
- Copyright Notice: All articles in this blog are licensed under unless otherwise stated.
GitHub Discussions