Basic Collections - Lists Continued
(Page 2 of 6 )
All sorts of problems could be caused by mixing types. What happens when one type is expected but another is retrieved? Running this code will raise a System.InvalidCastException since we've added an int to the arrayList:
foreach (string element in arrayList1)
{
Console.WriteLine(element);
}
Yes, we could fix this by checking each individual element to see if it is indeed a string, but this is quite messy:
foreach (object element in arrayList1)
{
string elementString = element as string;
if (elementString != null)
{
Console.WriteLine(elementString);
}
}
It's also important to remember that checking for the proper type is not free, especially in large collections. Surely, there must be a better, type-safe way! There is, in the form of generic collections. Generic collections are located in the namespace System.Collections.Generic. A generic list called List is available, and it works just like ArrayList except that only objects of a specific type can be put into it. Here, we create a List with string elements:
List<string> genericList1 = new List<string>() { "nine", "ten" };
Now, we know for sure that each element is a string. Attempting to add an object of any other type will raise an exception. Let's enumerate all of the elements:
foreach (string element in genericList1)
{
Console.WriteLine(element);
}
To determine how many elements are in a List, the Count property can be read. Here, we write the number of elements in genericList1 to the console:
Console.WriteLine(genericList1.Count);
Sometimes, it may be necessary to add an element into the middle of a List. Add only puts a given object at the end of the list. To create a new element anywhere within the list, use the Insert method. Here, we insert a new element into the second position:
genericList1.Insert(1, "nine and a half");
All elements to the right (that is, those with a greater index) are bumped up.
Removing an element from a List is quite simple. In order to remove an element at a given index, the RemoveAt method is used:
genericList1.RemoveAt(1);
It's also possible to remove a given object from the List by calling the Remove method. Note, however, that this only removes the first occurrence of the object:
genericList1.Remove("nine");
We can also remove all elements from a List using the Clear method:
genericList1.Clear();
Sorting in a List is very simple as well with the Sort method. Let's create a List called names that contains several names. Then, we'll sort them alphabetically:
List<string> names = new List<string>() { "David", "Adam", "Charles", "Jason" };
names.Sort();
We can also reverse the order of the elements in a List by calling the Reverse method:
names.Reverse();
Searching through a list can also be done through instance methods. To determine if a List contains a given object, the Contains method is used, which returns a boolean value indicating whether or not the object is in the list:
bool danielFound = names.Contains("Daniel");
If we need the index of an element, the IndexOf method can be used. It returns the index of the first occurrence of a given object. If the object is not found, it returns -1:
int jasonsLocation = names.IndexOf("Jason");
int chucksLocation = names.IndexOf("Chuck");
List also defines a BinarySearch method, which searches for a given object using a binary search algorithm. This, however, requires that the List to be searched is sorted. The method returns the index of the object, if found, or a negative number:
names.Sort();
int adamsLocation = names.BinarySearch("Adam");
int nicksLocation = names.BinarySearch("Nick");
No, a List isn't an array, of course, but you are able to copy the elements of a List to an array using the ToArray method:
string[] nameArray = names.ToArray();
Next: Queues >>
More ASP.NET Articles
More By Peyton McCullough