Home > University > Back to the Basics: List Manipulation

Back to the Basics: List Manipulation

First in the Back to the Basics series: List Manipulation! This is probably the most boring, and tedious thing for the beginner-coder, if not done properly. Today we’ll be covering this stuff, along with a Visual Studio 2008 project so you can experiment a bit yourself.

Let’s shed some light on the structure of the application first, so you know what we’re working with:

  • One central Order class. This contains all the properties related to the orders.
  • One central List<Order>, containing all the Orders we have stored in our application.
  • Various methods, ie. Insert, Update, Delete. These manipulate the objects in the list, in a straight-forward manner.

So, with that out of the way, there are a few things I highly recommend you read up on – it’ll make your life a lot easier!

We’ll be working with a List<T>, where T is the type of object the list holds. This can be – for example – a string, integer, you name it, but also an object, such as our Order object! A list is a Collection. There are multiple collections available, but for what we’re going to do today – a List will suffice in all our requirements. Read the (very short) article about collection on MSDN here. And next, you will want to read up on the List<T> specifically here. We’ll be using the foreach loop extensively too, so I _highly_ recommend you know what it’s doing, and why it is useful!

Let’s get going, shall we?

Step 1 – Setting up our project

To start your project, go to New -> New Project, select a Windows Forms Application, and name it whatever the hell you like.
After that, go to Project -> Add Class and add a file called Order.cs. That will be the main order object we’ll be working with.

Step 2 – Defining the Order object

There’s not much we can do with an empty object. Therefore, we’ll be giving it some “body”. First off, declare the Order class as public, by adding the “public” keyword before the class definition; as so: public class Order. The reason we do this is so that any application, including our own, which refers to our application can use the Order class.

Next,we’ll be declaring two properties in the Order object. If you wonder why I don’t declare a field and a property, it’s because a Property holds a field internally. This basically means they’re the same, and a property can hold a value like a field can – so there’s absolutely no need to declare a field here:

public class Order
{
/// <summary>
/// Basic constructor.
/// </summary>
/// <param name=”id”>Order ID</param>
/// <param name=”name”>Order Name</param>
public Order(int id, string name)
{
ID = id;
Name = name;
}

/// <summary>
/// The ID of the Order.
/// </summary>
public int ID { get; set; }

/// <summary>
/// The Order’s name.
/// </summary>
public string Name { get; set; }
}

This allows us to call Order.Name, and Order.ID! Isn’t it amazingly simple? If you’re wondering what get; set; means; it delcares what we can do with the property. The get accessor allows us to – logically? – GET the value of the property, and the set allows us to – stunningly – SET the value of the property. If we would declare them with just “get”, we can not change the property’s value. So Object.ID = 1; would throw an error at us, because we didn’t declare a set accessor. Easy enough, isn’t it? :-)

Step 3 – Declaring the Order list

First off, rename Form1 to Main. Then, open it up in the code editor (Right click -> View Code), and put the following code inside the class definition, but not inside a method:

public List<Order> Orders = new List<Order>();

This provides us with a basic list, which we can access to keep track of our orders.

Step 4 – Creating some objects to work with

Now that we have the list pointed down, we’ll need some objects to work with. At the same time, we’ll be using the Add() method of the Collection, so pay close attention, you may pick up a bit for later on. We’ll also be using a for loop. This isn’t as complicated as it looks, and I’ll explain it in the code. First off, double click inside the form, when viewing it in Design view. This will create a Main_Load(object sender, EventArgs e) in your code, which will be executed when the form loads. This is known as the load event, any code we put in it will be executed when the form loads.

Add the following foreach loop to that Load event:

// i = 0, if i is less or equal to 100, do i + 1.
for (int i=0; i<=100; i++)
{
// Add a new order, give it the ID of i, and the name ORDDER(i)
Orders.Add(new Order(i, “ORDER” + i));
}

Code should be self explanatory, together with the comments.

Step 5 – Creating a method to add an Order

This step is straight forward as can be. Basically, we want a method that takes two arguments: ID and Name. Then we create a new object which adds that to the list with Orders:

public void AddOrder(int id, string name)
{
Orders.Add(new Order(id, name));
}

Always – and I mean always – add a new instance of Order to the list, using the new keyword. As you can see, we are using the Add() method of the list to add an object to it.

Step 5 – Searching by ID

This step of the tutorial is a small step up from adding an object, as we actually have to loop through all the objects. This is where the foreach loop becomes key, so I hope you have read up on it, and know what it’s doing.

The concept is simple. We take the ID as a parameter of our method, then loop through all objects in the Objects list, and check if the ID == our ID argument.
If so, we add it to a local list of results, and at the end, we return that list. This is why the return type of the method is List<Order>. If you don’t know what a return type is, read up on MSDN here.

Anyway, onto the code:

public List<Order> Search(int id)
{
// The list we use for objects that matches the ID.
List<Order> ret = new List<Order>();

// Check all objects in the list, and see if the ID is what we’re looking for.
foreach (Order o in Orders)
{
if (o.ID == id)
{
// If so, add it to the return list.
ret.Add(o);
}
}

// Return the list of results.
return ret;
}

Looks a bit more complicated, I know. Just take a few minutes to comprehend it, and read the comments. It’s still pretty basic stuff!

Next thing is, how do we use this? That’s easy too, to search for the orders, we use the following code:

var res = Search(Convert.ToInt32(txt_SearchID.Text));

foreach (Order o in res)
{
lst_IDResult.Items.Add(o.ID + ” | ” + o.Name);
}

We’re using a ListBox called lst_IDResults to show our results. As you can see, we use another foreach loop. However, this time, we use the list that Search provided us with, not the global Orders list! Meaning the list only contains those objects we were searching! :-)

Step 6 – Updating a list entry

This one gets a bit tricky. It combines the search, and the listBox elements to update an item in the Order list.

If we want to update an object in the list, we’ll have to know what its index is. The index is simply defined as the number it has in the list; the first object added will have number 0, the second will have 1, the third will have 2, and so on. The index is zero-based, meaning it starts at 0, and goes up from there.

When we dump all the objects into a listBox, using a simple foreach loop, they will have the exact same index as they have in the Orders list. This means we can use the index of the listBox as a secure and narrowed down point for updating objects.

First off, add a new property to the Order object, called Index. It’s an int. We don’t add this to our constructor, as we’ll only use it for updating.
Also, add public Order curObj { get; set; } to your Main.cs file. This is the object we have selected for updating, and we use this for easy reference later on.

Now, we want to populate the listBox with all items that Orders holds. To do this, we use the following code in the Show Objects button:

// Clear the list.
lst_Update.Items.Clear();

foreach (Order o in Orders)
{
lst_Update.Items.Add(o.ID + ” | ” + o.Name);
}

Then, under the Select this Item button, we define the following:

// Sets the curObj to the index we have selected in the list.
curObj = Orders[lst_Update.SelectedIndex];

// Set the Index property to the index of this object in the listBox.
curObj.Index = lst_Update.SelectedIndex;

// Set the Textboxes to the object’s name and ID.
txt_OrderID.Text = curObj.ID.ToString();
txt_OrderName.Text = curObj.Name;

This uses the Index I was talking about earlier. If you are unsure about what the Index is, check the “Inserting elements” section of this page. And if still unsure, Google around a bit.

And finally, to execute the update:

// Make sure an item is selected.
if (curObj != null)
{
// Change the values.
Orders[curObj.Index].ID = Convert.ToInt32(txt_OrderID.Text);
Orders[curObj.Index].Name = txt_OrderName.Text;
}

There is really not much to explain about the update code, and it is one way of doing it, there are multiple ways to update items in a list.

I suggest you look up the methods of the List<T> collection, and do a Google search on how to achieve these various tasks aside from this tutorial. Maybe I have over-complicated it, I don’t know.

I’m attaching two pieces of source code, one written for this very tutorial, and one I had laying around. Both will demonstrate how to achieve these tasks perfectly, and they both work. Learn as much as you can from it, and read up on a dozen of tutorials on the internet, and you will be fine.

The source of this tutorial:
http://release.aevitas.in/BackToBasic-Lists.rar

Similar source I made earlier:
http://release.aevitas.in/PObjects.rar

Good luck!

Categories: University

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.