F:http://www.dotnetperls.com/list
List. Fossils from the past are in layers of rock. As time passes, new layers of rock are added. In a sense the fossil record is a list.
In a computer program, a List can be added to. New records (like layers of rock) can be appended to the end. In C# a list is initialized. It adjusts its size as needed.Initialize List
First example. Moving on from dinosaurs, here we have a C# List of ints. We add 4 prime numbers to our List. The values are stored in the order added.
Note:There are other ways to create, and add elements to, Lists—this is not the simplest.
Note 2:The angle brackets are part of the declaration type. They are not conditional (less or more than) operators.
Based on: .NET 4.6 C# program that adds elements to List using System.Collections.Generic; class Program { static void Main() { List<int> list = new List<int>(); list.Add(2); list.Add(3); list.Add(5); list.Add(7); } }
C# program that uses List, foreach-loop using System.Collections.Generic; class Program { static void Main() { List<int> list = new List<int>(); list.Add(2); list.Add(3); list.Add(7); // Loop through List with foreach. foreach (int prime in list) { System.Console.WriteLine(prime); } } } Output 2 3 7
Tip:Arrays use Length. But Lists use Count. To loop backwards, start with list.Count - 1, and decrement to >= 0.
C# program that uses for-loop using System; using System.Collections.Generic; class Program { static void Main() { List<int> list = new List<int>(new int[]{ 2, 3, 7 }); // Loop with for and use string interpolation to print values. for (int i = 0; i < list.Count; i++) { Console.WriteLine($"{i} = {list[i]}"); } } } Output 0 = 2 1 = 3 2 = 7
Clear:Here we use the Clear method, along with the Count property, to erase all the elements in a List.
ClearInfo:Before Clear is called, this List has 3 elements. After Clear is called, it has 0 elements.
Null:We can assign the List to null instead of calling Clear, with similar performance.
C# program that counts List using System; using System.Collections.Generic; class Program { static void Main() { List<bool> list = new List<bool>(); list.Add(true); list.Add(false); list.Add(true); Console.WriteLine(list.Count); // 3 list.Clear(); Console.WriteLine(list.Count); // 0 } } Output 3 0
Caution:The array element type must match the List element type or compilation will fail.
C# program that copies array to List using System; using System.Collections.Generic; class Program { static void Main() { int[] arr = new int[3]; // New array with 3 elements. arr[0] = 2; arr[1] = 3; arr[2] = 5; List<int> list = new List<int>(arr); // Copy to List. Console.WriteLine(list.Count); // 3 elements in List. } } Output 3
C# program that uses foreach using System; using System.Collections.Generic; class Program { static void Main() { // New list for example. List<int> primes = new List<int>(new int[] { 2, 3, 5 }); // See if List contains 3. foreach (int number in primes) { if (number == 3) // Will match once. { Console.WriteLine("Contains 3"); } } } } Output Contains 3
Note:IndexOf has two overloads. It works in the same way as string's IndexOf. It searches by value and returns the location.
C# that uses IndexOf using System; using System.Collections.Generic; class Program { static void Main() { List<int> primes = new List<int>(new int[] { 19, 23, 29 }); int index = primes.IndexOf(23); // Exists. Console.WriteLine(index); index = primes.IndexOf(10); // Does not exist. Console.WriteLine(index); } } Output 1 -1
Note:Setting a capacity sometimes improves performance by nearly two times for adding elements.
However:Adding elements, and resizing List, is not usually a performance bottleneck in programs that access data.
Note:It is unclear how TrimExcess feels about its status. I wouldn't want to upset its feelings.
The TrimExcess method does nothing if the list is at more than 90 percent of capacity.
TrimExcess: MSDNWarning:Be cautious with Predicates and Actions. These objects can decrease the readability of code.
Info:It checks the entire list—unless an element doesn't match and it returns false early.
ToArray:It requires the ToArray instance method on List. This ToArray is not an extension method.
Tip:The biggest advantage of Join here is that no trailing comma is present on the resulting string.
C# that joins List using System; using System.Collections.Generic; class Program { static void Main() { // List of cities we need to join. List<string> cities = new List<string>(); cities.Add("New York"); cities.Add("Mumbai"); cities.Add("Berlin"); cities.Add("Istanbul"); // Join strings into one CSV line. string line = string.Join(",", cities.ToArray()); Console.WriteLine(line); } } Output New York,Mumbai,Berlin,Istanbul
Keys:The Keys property returns an enumerable collection of keys. But a List of these elements is more usable.
C# that converts Keys using System; using System.Collections.Generic; class Program { static void Main() { // Populate example Dictionary. var dict = new Dictionary<int, bool>(); dict.Add(3, true); dict.Add(5, false); // Get a List of all the Keys. List<int> keys = new List<int>(dict.Keys); foreach (int key in keys) { Console.WriteLine(key); } } } Output 3, 5
Also:A Queue may allow simpler usage of the collection in our code. This may be easier to understand.
QueueC# that inserts into List using System; using System.Collections.Generic; class Program { static void Main() { List<string> dogs = new List<string>(); // Example list. dogs.Add("spaniel"); // Contains: spaniel. dogs.Add("beagle"); // Contains: spaniel, beagle. dogs.Insert(1, "dalmatian"); // Spaniel, dalmatian, beagle. foreach (string dog in dogs) // Display for verification. { Console.WriteLine(dog); } } } Output spaniel dalmatian beagle
Note:Sort acts upon elements depending on type. It is possible to provide a custom method.
Internally:This method invokes the Array.Reverse method. Many list methods are implemented with Array methods.
C# that uses Reverse using System; using System.Collections.Generic; class Program { static void Main() { List<string> list = new List<string>(); list.Add("anchovy"); list.Add("barracuda"); list.Add("bass"); list.Add("viperfish"); // Reverse List in-place, no new variables required. list.Reverse(); foreach (string value in list) { Console.WriteLine(value); } } } Output viperfish bass barracuda anchovy
C# that gets ranges from List using System; using System.Collections.Generic; class Program { static void Main() { List<string> rivers = new List<string>(new string[] { "nile", "amazon", // River 2. "yangtze", // River 3. "mississippi", "yellow" }); // Get rivers 2 through 3. List<string> range = rivers.GetRange(1, 2); foreach (string river in range) { Console.WriteLine(river); } } } Output amazon yangtze
However:Using structs will actually decrease performance when they are used as parameters in methods such as those on the List type.
StructsC# that uses var with List using System.Collections.Generic; class Program { static void Main() { var list1 = new List<int>(); // Var keyword used. List<int> list2 = new List<int>(); // This is equivalent. } }
List's syntax is at first confusing. But we become used to it. In most programs lacking strict memory or performance constraints, List is ideal.