C# Tutorial - Generic List

Skill

C# Tutorial - Generic List

Posted in:

Arrays are a staple in programming, but nowadays in this world of dynamic content, you often times need something more flexible. This is where the other C# collections come into play. A long time ago, I did a tutorial on a collection called a dictionary, but those types of collection have a niche. Today, I am going to go over its older brother and sensei of sorts, the List.

Lists are a lot more flexible than dictionaries, and are quicker and slightly simpler to use. The biggest advantage to both collections are that they are dynamic, allowing you to add entries as you go. Arrays are a predetermined size, while lists and other such collections are not. This allows us to add as many entries into the list as we want, which is a gigantic advantage.

To start, we are going to use our old friend Visual Studio, and of course C#. Once you have a C# Windows Forms project started up (I am using Visual C# 2008 Express, but it really does not matter in this tutorial, as long as you are using Visual Studio), all you need to do to the default form is add a Rich Textbox. This will display our information, rather than having a popup message for basic output.

The Windows Form with our textbox.

The Windows Form you should have.

Once you have a textbox on your form, we need to go ahead and start adding code. All of our code today will be in a method, as part of the basic form class that is created by default. So you will have something like this:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
  public partial class Form1 : Form
  {
    public Form1()
    {
      InitializeComponent();
    }

    public void DoList()
    {
    }
  }
}

Take notice at the using statements at the top of the code. These are all put there by default, but if you are missing the using System.Collections.Generic;, make sure you add it because you will not be able to use a list without including these collections.

The first thing we need to do is create our list, which can be do with the following code:

List<string> theList = new List<string>();

Notice the brackets after the List identifier, whatever is inside these brackets is the type of the objects the list will hold. In our case, we are creating a list of string objects, for now an empty list. In order to fill this list, we are going to create a simple loop and add to our list. To add to the list, there is actually a really simple method called (you guessed it) Add():

for (int i = 0; i < 11; i++)
{
  theList.Add("List Item #" + (i + 1).ToString());
}

All we are doing is taking the list and adding an item to it every iteration of the loop. For each iteration we are adding a new string object, which is set to the current iteration +1, making it so our first item is 1 and not 0. Just like an array, lists are indexed, starting at 0. This means that we can add a line such as:

richTextBox1.Text = "1st entry: " + theList[0] + "\n";

And it displays the first item in our list. But what if we want to output everything all at once? This is almost as simple. For that we use the string object, taking advantage of the static method join() which allows us to join the elements of an array. Wait, an array? Yes, we have to have an array to use the join() method, but thankfully the list object has a conversion for that. The toArray() will convert a list object to an array, giving us exactly what we need. The join call would look something like so:

richTextBox1.Text += string.Join(", ", theList.ToArray<string>());

The first argument is the seperator, and the second is the array to join, which in turn is our list conversion call. Notice we have to pass the type of array we want to convert to, but for simplicity sake we are just using a string array. This call would output all of our list items to the textbox. After one more little text addition, the final method looks like this:

public void DoList()
{
  List<string> theList = new List<string>();

  for (int i = 0; i < 11; i++)
  {
    theList.Add("List Item #" + (i + 1).ToString());
  }

  richTextBox1.Text = "1st entry: " + theList[0] + "\n";
  richTextBox1.Text += "Full List Contents:\n";
  richTextBox1.Text += string.Join(", ", theList.ToArray<string>());
}

A small, simple method that is the perfect example of what lists are all about. They are dynamic, flexing to what you need them for. Although they are limited by their type, their size is only limited by the computer on which they are used. But, before we part, we have to call this method somewhere. Right below the initialization is the perfect place:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
  public partial class Form1 : Form
  {
    public Form1()
    {
      InitializeComponent();
      DoList();
    }

    public void DoList()
    {
      List<string> theList = new List<string>();

      for (int i = 0; i < 11; i++)
      {
        theList.Add("List Item #" + (i + 1).ToString());
      }

      richTextBox1.Text = "1st entry: " + theList[0] + "\n";
      richTextBox1.Text += "Full List Contents:\n";
      richTextBox1.Text += string.Join(", ", theList.ToArray<string>());
    }
  }
}

The output.

Our textbox is filled with the list contents!

So, this is going to create a list, fill it, and output its contents all right after the form is created. While simple in concept, you can do a lot with lists, including creating a list of lists or a list of arrays. I hope this shows you at least a small part of the advantages of lists. Just remember, when you need coding help, all you have to do is Switch On The Code.

wexoni
06/16/2010 - 08:35

YOU ARE THE BEST.

I was making a complex wpf animation that uses generic lists... and I was having a issue how to access a specific element of the list... I looked and looked, and as usually the answer was right here on this site.

Simple as this theList[0];

Thank you again

reply

Tanner
06/17/2010 - 12:40

Good explanation.

Would you say that a list<list<string>> (multi dimensional string list) would usually be faster to iterate over than a multi dimensional array?

I like the generic interfaces that list supports especially when it comes to binding to UI items but i've used arrays for years and am very comfortable with them.

reply

The Reddest
06/17/2010 - 13:06

Depends on how you iterate the list. If you use foreach, the array will be faster. If you use a for loop, they will be nearly the same.

reply

Add Comment

Put code snippets inside language tags:
[language] [/language]

Examples:
[javascript] [/javascript]
[actionscript] [/actionscript]
[csharp] [/csharp]

See here for supported languages.

Javascript must be enabled to submit anonymous comments - or you can login.
CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.