#834 – Use a Generic List to Store a Collection of Objects
May 1, 2013 2 Comments
You can use the List<T> class, defined in System.Collections.Generic, to store a list of objects that all have the same type. This generic list is one of several collection classes that allow you to store a collection of objects and manipulate the objects in the collection.
You can think of a List<T> as an array that grows or shrinks in size as you add or remove elements. You can easily add and remove objects to a List<T>, as well as iterate through all of its elements.
You can store a collection of either value-typed or reference-typed objects in a List<T>.
// Define a list of integers List<int> favNumbers = new List<int>(); // Add a couple numbers to the list favNumbers.Add(5); favNumbers.Add(49); favNumbers.Add(8); favNumbers.Add(0); // Iterate through the list to get each int value foreach (int i in favNumbers) Console.WriteLine(i); // Remove 1st element (at position = 0) favNumbers.RemoveAt(0);
Pingback: Dew Drop – May 1, 2013 (#1,538) | Alvin Ashcraft's Morning Dew
“You can use the List class, defined in System.Collections.Generic, to store a list of objects that all have the same type.”
“You can think of a List as an array that grows or shrinks in size as you add or remove elements.”
Nice, succinct explanation! Too many references (Microsoft’s being one of the worst) make this simple concept so complicated.