Using the List Object in C#

A List is a System.Collection object that allows you to hold multiple values of the same type in a single variable. Because of the type-safety it provides, the List object has replaced the ArrayList as the go-to choice for storing like elements.

To declare a list, you use the List keyword followed by a placeholder for the data type of the objects that will exist in the list. To initialize a list, you must use the new keyword, as seen in the following example.

You need to use what is known as “generic syntax” to tell Visual Studio what type of elements the list will store. Generic syntax utilizes the angle brackets < > as a place holder for the datatype value.

 List<int> listOne = new List<int>();
 List<string> listTwo = new List<string>();
 List<DateTime> listThree = new List<DateTime>();

In this example, listOne will hold a collection of integers, listTwo will hold strings, listThree holds a collection of DateTime objects.

There is no requirement to declare the number of elements the list will contain since it can grow and shrink dynamically. As you add elements, it will expand to fit them.


Adding List Elements

If you want, you can add items to the list when you initialize it by supplying a comma-separated list between the curly braces { }. Just make sure you have a semi-colon; after the closing brace.

 List<string> employees = new List<string>()
 {
 "Steve",
 "Mary",
 "Kate", 
 "Geoff",
 "Presty"
 };

However, you don’t need to add your elements this way. You can use the Add() method of the List object to insert as many elements as you want.

 List<DateTime> holidayDates = new List<DateTime>();
 
 holidayDates.Add(DateTime.Parse("01/01/2000"));
 holidayDates.Add(DateTime.Parse("03/17/2000"));
 holidayDates.Add(DateTime.Parse("07/04/2000"));
 holidayDates.Add(DateTime.Parse("12/25/2000"));  

With the AddRange() method, you can add a range of elements to the list at one time. For example, if you wanted to create a list to store your next lottery ticket numbers but wanted to make sure your lucky numbers were always part of the list, your code would look something like this.

 List<int> lotteryNumbers = new List<int>();
 int[] myLuckyNumbers = new int[] { 17, 21, 33 };
 lotteryNumbers.AddRange(myLuckyNumbers);
 lotteryNumbers.Add(12);
 lotteryNumbers.Add(45);
 lotteryNumbers.Add(49); 

*** If you happen to win with these numbers feel free to send a portion of your winnings my way ***

Using Add() and AddRange() will add the elements to the end of the list. There may be times where you want to insert an element at a particular location in a list. To do that, you would use the Insert() method.

The Insert method allows you to specify at which index you would like to add your elements.

Let’s say that somewhere in your application, a grocery list is populated with the following code.

 List<string> groceryList = new List<string>()
 { 
 "milk",
 "eggs",
 "cheese",
 "bread",
 "cereal",
 "crackers"
 };

As you can see, it is seemingly ordered by the grocery category with “dairy” being at the beginning of the list. What do you do if another part of the application allows the user to enter the value “yogurt”? If you use groceryList.Add(“yogurt”), and it will be stored after “crackers” when you want to save it after “cheese.”

At this point, you would use the Insert method. Insert allows you to specify at which index you want to insert the value.

 groceryList.Insert(3, "yogurt");

Since the first element of the list has the index of 0, inserting the new element with the index of 3 will place it between “cheese” and “bread.”

Accessing, Modifying, and Displaying List Elements

If you wanted to do something with a particular element in the list, you could access it by using its index value.

 DateTime firstHoliday = holidayDates[0];
 Console.WriteLine("The last holiday of the year is " + holidayDates[3]);

You also use the index if you wanted to update the value in a list.

 lotteryNumbers[4] = 39;

What happens if you don’t know the index of the element you want to access? How would you go about finding it?

If you are looking for the index of the last element in the list, you can use the Count property of the List object.

Count will return an integer with the number of elements in the list.

 Console.WriteLine("There are " + groceryList.Count + " items on the grocery list");

Count is also useful to provide you with the index value of the last element in the list. If you don’t know how many elements are in the list, you can just count them. Because a list uses zero-based indexing, you will need to subtract one from the count to get the actual index.

 int holidayCount = holidayDates.Count;
 Console.WriteLine("The last holiday of the year is " + holidayDates[holidayCount - 1]);

Sometimes you know the value of the element but need the index to update its value. The IndexOf () method searches the list for a value and returns the index of that element.

 int breadIndex = groceryList.IndexOf("bread");
 groceryList[breadIndex] = "wheat bread";

IndexOf starts with the first element of the list (index = 0) and navigates through the list until it finds the value you are seeking. Sometimes, you don’t want to know when it first appears in the list. Instead, you want to update the element in which it appears last. The LastIndexOf () method will navigate the elements from the largest index and return the index of the first time it finds that value.

Removing List Elements

To empty all of the elements in a list, you use the Clear() method. Clear does precisely that. It clears out the collection.

 holidayDates.Clear();

What if you only want to remove a particular element from the list? How to do that would depend on what information you have about that element.

If you know the value of the element but not the index, you want to use the Remove() method.

 employees.Remove("Kate");

If you know the index of the element you want to remove, you use the RemoveAt() method.

 groceryList.RemoveAt(3);

If you want to remove a group of elements and you know the index of the first element, you use the RemoveRange() method.

 groceryList.RemoveRange(3, 10);

Just make sure you don’t try to remove more elements than exist. If you try, your application will crash with a message stating that “Offset and length were out of bounds.

Additional Methods

There are several more methods available when you use the List object that are not covered in this post.

The Sort() and Reverse() methods are discussed in the post discussing Foreach loops. The post about conditional expressions mentions the Contains() method. Find() and Exists() require the knowledge of predicates. There is a post for that topic at this time.


60 views2 comments

Recent Posts

See All