Skip to main content

C# Tutorial - Generic List [Beginner]


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 senses 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 Studio 2010 Ultimate, 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 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 separator, 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>());
    }
  }
}
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.

Source Files:
Lists.zip

Comments

Popular posts from this blog

C# Snippet - Shuffling a Dictionary [Beginner]

Randomizing something can be a daunting task, especially with all the algorithms out there. However, sometimes you just need to shuffle things up, in a simple, yet effective manner. Today we are going to take a quick look at an easy and simple way to randomize a dictionary, which is most likely something that you may be using in a complex application. The tricky thing about ordering dictionaries is that...well they are not ordered to begin with. Typically they are a chaotic collection of key/value pairs. There is no first element or last element, just elements. This is why it is a little tricky to randomize them. Before we get started, we need to build a quick dictionary. For this tutorial, we will be doing an extremely simple string/int dictionary, but rest assured the steps we take can be used for any kind of dictionary you can come up with, no matter what object types you use. Dictionary < String , int > origin = new Dictionary < string , int >();

C# Snippet - The Many Uses Of The Using Keyword [Beginner]

What is the first thing that pops into your mind when you think of the using keyword for C#? Probably those lines that always appear at the top of C# code files - the lines that import types from other namespaces into your code. But while that is the most common use of the using keyword, it is not the only one. Today we are going to take a look at the different uses of the using keyword and what they are useful for. The Using Directive There are two main categories of use for the using keyword - as a "Using Directive" and as a "Using Statement". The lines at the top of a C# file are directives, but that is not the only place they can go. They can also go inside of a namespace block, but they have to be before any other elements declared in the namespace (i.e., you can't add a using statement after a class declaration). Namespace Importing This is by far the most common use of the keyword - it is rare that you see a C# file that does not h

C# WPF Printing Part 2 - Pagination [Intermediate]

About two weeks ago, we had a tutorial here at SOTC on the basics of printing in WPF . It covered the standard stuff, like popping the print dialog, and what you needed to do to print visuals (both created in XAML and on the fly). But really, that's barely scratching the surface - any decent printing system in pretty much any application needs to be able to do a lot more than that. So today, we are going to take one more baby step forward into the world of printing - we are going to take a look at pagination. The main class that we will need to do pagination is the DocumentPaginator . I mentioned this class very briefly in the previous tutorial, but only in the context of the printing methods on PrintDialog , PrintVisual (which we focused on last time) and PrintDocument (which we will be focusing on today). This PrintDocument function takes a DocumentPaginator to print - and this is why we need to create one. Unfortunately, making a DocumentPaginator is not as easy as