C# Lists Introduction


This entry is part 1 of 5 in the series C# Lists

The post C# Introduction lists all of the series of posts we have at this site.

What are Lists? Lists are similar to arrays, but arrays have a fixed size. Once you create an array you can cannot change the array’s size. Both arrays and lists store a bunch of objects of the same type. Lists are useful when we are unsure of how many objects we will need storage for. We need to know the type of object, but not the number of objects. Lists are have a dynamic size. One great thing about Lists is that you can iterate through them using foreach. Normally, we would prefer to work with lists over arrays.

Generic Types

Lists are generic types, as indicated by the angle brackets <>. Inside the angle brackets you specify the type. We can create a list of anything. We can create a list of any of the primitive types such as strings or integers. We can create a list of classes. You can create a class called Product and create a list of Products. In the next post in this series we illustrate a list of customers.

Generics is actually an advanced topic but lists are easy to use. The code below creates a list of integers.

Object Initializer Syntax

The third line of code below uses object initializer syntax

var myIntegers = new List<int>();
List<int> myIntegers = new  List<int>();
// below is the object initializer syntax
var myNumbers = new List<int>() { 1, 2, 6, 3};

Methods

Here are some useful methods available for the List class.

  • Add()
  • AddRange()
  • Remove()
  • RemoveAt()
  • IndexOf()
  • Contains()
  • Count

In order to use Lists you will need to be sure that you have the following line of code at the top of your file. This code will import the namespace. It is probably already there.

using System.Collections.Generic;

Below is an example of some code using Lists. Notice that we can add an array to our List of numbers with AddRange(). So in the code below we demonstrate a few items: object initialization syntax, generics (as you can see with the two angle brackets < >), Add(), AddRange(), foreach and Count().

var numbers = new List<int>() {1, 2,3,4};
numbers.Add(1);
numbers.AddRange(new int[3] {5, 6, 7}); 
foreach (var number in numbers)
     Console.WriteLine (number);
Console.WriteLine ("Number of Integers: " + numbers.Count);
numbers.Remove(1)

Remove

There is a rule in C# that says we cannot modify (remove) a list inside a foreach loop. We need to use a for each loop instead. Below is an example of that.

    class Program
    {
        static void Main(string[] args)
        {
            var numbers = new List<int>() {1, 2,3,4};
            numbers.Add(1);
            numbers.AddRange(new int [3] {5, 6, 7});
            foreach (var number in numbers) Console.WriteLine(number);
                
            Console.WriteLine ("Number of Integers: " + numbers.Count);

            // removes the FIRST occurrance of 3 in the list
            numbers.Remove(3); 
            foreach (var number in numbers) Console.WriteLine(number);
            // we are not allowed to Remove() within a foreach loop
            // so we use a regular for loop with a counter

            // the indes is zero-based
            Console.WriteLine ("The first integer is: " + numbers[0]);

            // remove all of the ones (1) from the list
            for (var i = 0; i < numbers.Count; i++)
            {
                if (numbers[1] == 1) numbers.Remove(numbers[i]);
            }
            foreach (var number in numbers) Console.WriteLine(number);

            Console.ReadKey();
        }
    }

Below is another example.

namespace MikeList {  // Generics - List<T> page 312
    class Program  {  // Chapter 12, Written by Mike
        // Compare Ch11Ex02. This is much easier than 
        // deriving a class from CollectionBase and then
        // implement the required methods.
        static void Main(string[] args) {
            List<string> myList = new List<string>();
            string myString = "hello world";
            string myOtherString = "hi world";
            string myThirdString = "a message for you";
            myList.Add(myString);
            myList.Add(myOtherString);
            myList.Add(myThirdString);
            WriteLine($"{myList[0]} \n");  // the first one
            foreach (string myStrg in myList)
                { WriteLine(myStrg); }
            myList.Sort();   WriteLine("\n");
            foreach (string myStrg in myList)
                { WriteLine(myStrg); }
            ReadKey();
        }
    }  // using System.Collections.Generic;
}
Series NavigationC# Lists String Repository >>