List Any in C#
C# List ExamplesCreate a new List and add elements to it. Loop over its elements with for and foreach. List. Programs often do simple things, like read in numbers. With a List, we can Add() these items as we encounter them, and this C# class handles the implementation details. List details. The List is initialized with the new keyword. When we call Add, the List adjusts its size as needed. It is used in nearly all larger C# programs. Initialize List Initialize. Here we create 2 separate lists of ints. We add 4 prime numbers to each List. The values are stored in the order added—2, 3, 5 and then 7. Version 1 We call Add() 4 times with the number as the argument. The end count of the list is 4. List Add Version 2 This code adds all 4 numbers in a single expression—it is easier to read, and the code generated is the same. C# program that uses List, Add, initializer using System; using System.Collections.Generic; class Program { static void Main() { // Version 1: create a List of ints. // ... Add 4 ints to it. var numbers = new ListForeach-loop. This is the clearest loop when no index is needed. It automatically sets each element to a name we specify—here we use the identifier "prime." Part A We use the "foreach" keyword and declare a variable that is assigned to each element as we pass over it. Part B In the foreach-loop, we access the "prime" variable, which is the current element. We print each int to the screen. C# program that uses foreach, List using System.Collections.Generic; class Program { static void Main() { ListIndexes, for-loop. A List has elements like an array, and they are accessed by indexes starting at zero. For iteration, we can use these indexes in a for-loop. Part 1 Here we create a list of 3 elements, and print its first element to the console (using index 0). Part 2 We use a for-loop, beginning at 0. We end when we reach Count—the last index accessed is Count-1. For Part 3 We print each element index with Console.WriteLine. We use a string interpolation expression to format the string. C# program that uses List indexes and for-loop using System; using System.Collections.Generic; class Program { static void Main() { // Part 1: create List. // ... Print the first element of the List. ListFor-loop, reverse. Much like an array, we can access the elements in a List in any way we like. We can loop over the List elements in reverse with a for-loop. Start For a reverse loop, we must access the last element first, so we get the Count and subtract one from it. This is the last index. C# program that uses for reverse, List using System; using System.Collections.Generic; class Program { static void Main() { var votes = new ListAddRange, InsertRange. For adding many elements at once, we use the InsertRange and AddRange methods. InsertRange can insert at an index, while AddRange adds at the end. AddRange, InsertRange Tip The first argument to InsertRange is the index where we want to insert new elements. The second is an IEnumerable (a string array). Result We create a List of 2 strings, then add 2 strings from an array to index 1. The result List has 4 strings. C# program that uses InsertRange using System; using System.Collections.Generic; class Program { static void Main() { // Create a list of 2 strings. var animals = new ListCount, clear. To get the number of elements, access the Count property. This is fast—just avoid the Count extension method. Count, on the List type, is equal to Length on arrays. Part A We create a List, add 3 elements, and then Count them. The correct value (3) is printed. Part B Here we use the Clear method to erase all the elements in a List. The List then has zero elements. List Clear C# program that counts and clears List using System; using System.Collections.Generic; class Program { static void Main() { // Part A: build up List, and Count its elements. ListCopy array. Here we create a List with elements from an array. We use the List constructor and pass it the array. List receives this parameter and fills its values from it. Warning The array element type must match the List element type or compilation will fail. CopyTo The List constructor can be used to copy a collection (like an IEnumerable). But for ranges, CopyTo can be used. List CopyTo C# program that copies array to List using System; using System.Collections.Generic; class Program { static void Main() { // Create new array with 3 elements. int[] array = new int[] { 2, 3, 5 }; // Copy the array to a List. ListList parameter. Lists do not exist just to be allocated and looped over. We want to test and examine elements to solve real-world problems in our programs. Main Here we pass a List to ContainsValue300. The List can be passed as an argument—only the reference, not all elements, are copied. ContainsValue300 This method uses a foreach-loop, which tests to see if 300 is in a list of numbers. If Result The values List contains the value 300, so our custom method returns the boolean true. C# program that uses foreach using System; using System.Collections.Generic; class Program { static void Main() { var values = new ListIndexOf. This determines the element index of a certain value in the List collection. It searches for the first position (from the start) of the value. Note IndexOf has two overloads. It works in the same way as string's IndexOf. It searches by value and returns the location. C# program that uses IndexOf using System; using System.Collections.Generic; class Program { static void Main() { var primes = new ListContains, Find and Exist. Similiar to IndexOf, these methods provide searching of the List. They vary in arguments accepted. With Predicates, we influence what elements match. List Contains List Find, Exists C# program that uses built-in Contains method using System; using System.Collections.Generic; class Program { static void Main() { var values = new ListForEach. This is a method. Sometimes we may not want to write a traditional foreach-loop. Here ForEach is useful. It accepts an Action. Example We have a 2-element string List. Then we call ForEach with a lambda that writes each element "a" to the console. C# program that uses ForEach on List using System; using System.Collections.Generic; class Program { static void Main() { var animals = new ListTrueForAll. This method accepts a Predicate. If the Predicate returns true for each element in the List, TrueForAll() will also return true. And TrueForAll() checks the entire list—unless an element doesn't match (it has an early exit condition). C# program that uses TrueForAll on List using System; using System.Collections.Generic; class Program { static void Main() { var numbers = new ListJoin string list. Next we use string.Join on a List of strings. This is helpful when we need to turn several strings into one comma-delimited string. 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# program that joins List using System; using System.Collections.Generic; class Program { static void Main() { // List of cities we need to join. ListKeys in Dictionary. We use the List constructor to get a List of keys from a Dictionary. This is a simple way to iterate over Dictionary keys (or store them elsewhere). Keys The Keys property returns an enumerable collection of keys. But a List of these elements is more usable. C# program that converts Keys using System; using System.Collections.Generic; class Program { static void Main() { // Populate example Dictionary. var dict = new DictionaryInsert. This method places an element at an index. We pass in the index (an integer) and the element we wish to place in the list. Insert can cause performance problems. List Insert Part 1 We create an empty string list, and then add 2 string elements to it (these are the names of dogs). Part 2 We call insert to place a new dog name as the second element. Later elements ("beagle") now come after the new second element. Queue A Queue may allow simpler usage of the collection in our code. This may be easier to understand. Queue C# program that inserts into List using System; using System.Collections.Generic; class Program { static void Main() { // Part 1: call add to populate list. ListRemove. With this method we eliminate the first matching element in the List. If we pass the value 20 to Remove, the first element in the list with value 20 is removed. Info We can call Remove with an argument that does not occur in the list. This will not cause an exception. List Remove RemoveAll We can remove more than 1 element at once with the RemoveAll method. RemoveAll C# program that uses Remove using System; using System.Collections.Generic; class Program { static void Main() { var numbers = new ListReverse. With this method no sorting occurs—the original order is intact but inverted. The strings contained in the List are left unchanged. Array.Reverse Internally This method invokes the Array.Reverse method. Many list methods are implemented with Array methods. C# program that uses Reverse using System; using System.Collections.Generic; class Program { static void Main() { ListGetRange. This returns a range of elements in a List. This is similar to the Take and Skip methods from LINQ. It has different syntax. The result List can be used like any other List. C# program that gets ranges from List using System; using System.Collections.Generic; class Program { static void Main() { ListEqual. SequenceEqual is a method from System.Linq. It tells us whether 2 collections have the same exact elements. The number of elements and order must be the same. SequenceEqual Also If unordered Lists should be considered equal, we can write a custom method. We can sort and then compare. List Equals C# program that uses SequenceEqual using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { var numbers = new ListVar keyword. This shortens lines of code, which sometimes improves readability. Var has no effect on performance, only readability for programmers. Var C# program that uses var with List using System.Collections.Generic; class Program { static void Main() { // Var keyword used. var list1 = new ListBenchmark, create List. Suppose we want to create a List of 3 elements with an initializer. If we can use an array instead, the program will be faster. Version 1 We create a string array of 3 elements with an array initializer. We test its length. Initialize Array Version 2 This code creates a List of strings with an initializer. The List is an additional object—performance is affected. Result It is faster to allocate an array of strings—this was tested in 2021, on .NET 5 for Linux. C# program that tests List creation time using System; using System.Collections.Generic; using System.Diagnostics; class Program { const int _max = 1000000; static void Main() { // Version 1: create string array with 3 elements in it. var s1 = Stopwatch.StartNew(); for (int i = 0; i < _max; i++) { var items = new string[] { "bird", "frog", "fish" }; if (items.Length == 0) { return; } } s1.Stop(); // Version 2: create string list with 3 elements in it. var s2 = Stopwatch.StartNew(); for (int i = 0; i < _max; i++) { var items = new ListCapacity. We can use the Capacity property on List, or pass an integer to the constructor (which sets an initial capacity) to improve allocation performance. Capacity Sort. This orders the elements in the List. For strings it orders alphabetically. For integers (or other numbers) it orders from lowest to highest. Sort List BinarySearch. This method implements the binary search algorithm. Binary search uses guesses to find the correct element faster than linear searching. BinarySearch List Combine lists. With Concat, a method from the System.Linq namespace, we can add one list to another. Only a single method call is required. Concat Remove duplicates. With Distinct() we can remove duplicates from a List. Other algorithms, that use Dictionary, can be used to scan for and erase duplicates. Duplicates Notes, List. This generic (like all others) is created with a type parameter. List is powerful: it provides flexible allocation and growth. Lists can be nested, static, or assigned to null. Nested List Null List Static List A summary. 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. © 2007-2022 sam allen. see site info on the changelog. |