Author : MD TAREQ HASSAN | Updated : 2021/03/22

List syntax

// Creating list
List<string> cities =  new List<string>();

var cities = new List<string>();               // type inference
cities.Add("Tokyo");
cities.Add("Seoul");


// Initialization 
List<int> digits = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; 
List<Cat> cats = new List<Cat> {
    new Cat{ Name = "Sylvester", Age=8 },
    new Cat{ Name = "Whiskers", Age=2 }
};


// Property
list.Count                      // FYI => array.Length


// Empty check
if(!myList.Any())
{

}

// O(1) operations
list[index]                     // indexer
list.ElementAt(index)           // slower than indexer
list.ElementAtOrDefault(index)

list.Add(T)  // at the end
list.AddRange(IEnumerable<T>)  // at the end
list.RemoveAt(Count - 1)


// O(n) operations
list.Contains(T item);
list.Sort();
list.Reverse();
list.IndexOf(T item);         // first occurrence

Links

Count

// List
var count = itemList.Count;


// For IEnumerable
var count = Enumerable.Count(itemList)
var count = new List<ItemType>(itemList).Count;

List to string

var combindedString = String.Join(" ", list); 

String to list

List<string> words = myString.Split(delimiters, StringSplitOptions.RemoveEmptyEntries).ToList();
// T[] delimiters, T == Char, string

List<string> words = myString.Split(" ").ToList()

List to array

string[] arr = list.ToArray();

Array to list

var list = new List<T>(array); // new List<T>(IEnumerable)
var list = array.ToList();
var list = new List<T>();
list.AddRange(array);

List to dictionary

var dict = list.ToDictionary(x => x, x => x);
// to avoid duplicate key
var dict = list.Distinct().ToDictionary(x => x, x => x);
var dict = list.ToLookup(x => x);

Dictionary to list

var keyList = dictionary.Keys.ToList();
var valList = dictionary.Values.ToList();

// key value pair
List<KeyValuePair<string, int>> list = dictionary.ToList();
foreach (KeyValuePair<string, int> pair in list){
  Console.WriteLine(pair.Key);
  Console.WriteLine(pair.Value);
}

// when values are nested list
Dictionary<K, List<V>> dictionary = GetDictionary();
List<List<V>> nestedList = dictionary.Values;
List<V> list = nestedList.SelectMany(item => item).ToList();

Remove duplicate without using HashSet

var myList = new List<int>() {1, 2, 3, 4, 3, 2, 1, 5, 1};
myList = myList.Distinct().ToList();

Get duplicate items using LINQ

List<String> duplicates = list.GroupBy(item => item)
                             .Where(g => g.Count() > 1)
                             .Select(g => g.Key)
                             .ToList();

Flattening nested list

List<List<V>> nestedList = GetNestedList();
List<V> list = nestedList.SelectMany(item => item).ToList();