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# 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...

C# WPF Tutorial - Implementing IScrollInfo [Advanced]

The ScrollViewer in WPF is pretty handy (and quite flexible) - especially when compared to what you had to work with in WinForms ( ScrollableControl ). 98% of the time, I can make the ScrollViewer do what I need it to for the given situation. Those other 2 percent, though, can get kind of hairy. Fortunately, WPF provides the IScrollInfo interface - which is what we will be talking about today. So what is IScrollInfo ? Well, it is a way to take over the logic behind scrolling, while still maintaining the look and feel of the standard ScrollViewer . Now, first off, why in the world would we want to do that? To answer that question, I'm going to take a an example from a tutorial that is over a year old now - Creating a Custom Panel Control . In that tutorial, we created our own custom WPF panel (that animated!). One of the issues with that panel though (and the WPF WrapPanel in general) is that you have to disable the horizontal scrollbar if you put the panel in a ScrollV...