Upload
others
View
2
Download
0
Embed Size (px)
Citation preview
Module 201 Object Oriented Programming
Lecture 11 – String Arrays and Collections
Len Shand
Arrays
Arrays and Text Collections
Previously you saw how to place numbers into an array. But you can also place strings of text.
Add a new button to your form, and set the Text property to String Arrays. Then double click your button to get at the code.
To place text into an array, you set up your array as you normally would, except you use the keyword string instead of int.
Like this: string[] arrayStrings; arrayStrings = new string[5]; So the above code would set up an array that is going to hold strings of text. There will be five positions in the array. Add the code above to your button.
To place values in the array, it’s just normal variable assignment, with a pair of square brackets after the variable name:
arrayStrings[0] = "This"; arrayStrings[1] = "is"; arrayStrings[2] = "a"; arrayStrings[3] = "string"; arrayStrings[4] = "array"; Add the above to your code.
To access the values in each position of your array, you could use a for loop, as you have been doing. Like this:
for (int i = 0; i != (arrayStrings.Length); i++) { listBox1.Items.Add( arrayStrings[i] ); } Don’t add this to your code...
But there’s another type of loop that you haven’t met yet called a foreach loop. This comes in handy when you’re trying to access items in a collection, which you’ll see how to do shortly.
But add this to your code, instead of a for loop: foreach ( string arrayElement in arrayStrings ) { listBox1.Items.Add( arrayElement ); }
Notice where all the keywords are in the loop code above, the ones in bold. You start with the foreach keyword, followed by a pair of round brackets. In between the round brackets, we have this: string arrayElement in arrayStrings
This is really two parts in one. In the first part, string arrayElement, you set up a new variable. The new variable will hold the elements (array values) from each position in your array. The second part, in arrayStrings, is where you tell C# the name of the array or collection you want to access. C# will then loop round all the positions in your array, and place the value at that position into your new variable (arrayElement, for us). You can then do something with the value in the new variable. All we are doing in our loop is to display the value in a list box.
Notice that for the array, you don’t need the square brackets anymore. The neat thing about foreach loops is that you don’t need to use index numbers, like you do with ordinary for loops. Run your programme and click the button.
Arrays are very useful for holding lots of values under the same name. But there is also something called a Collection that does a similar job. In fact, there's an inbuilt group of Classes in C# specifically for Collections. They can be quite powerful.
With an array, you store data of the same type. An array set up as int can hold numbers, but not letters. And an array set up as string can't hold numbers.
So you can't do this, for example: arrayPos[0] = 1; arrayPos[1] = "two"; The first position holds a number and the second position holds text. C# won't let you do this in an array. But you can do it in a collection known as a Hashtable.
Collections can also make it easier to do things like sorting the data in your lists, deleting items, and adding more items. We'll start with the collection class called ArrayLists.
You use an ArrayList when your collection may need items adding to it, deleting from it, or needs sorting. For example, suppose you are teacher with a class of ten children:
You could keep a list of the children’s names, add new students, delete ones who leave, and even sort them into brightest and dimmest!
If you used a normal array, it would be difficult to do these things.
So start a new C# project. Add a button and a listbox to your new form. Double click the button to get at the coding window.
Now have a look near the top and you’ll see a list of using statements
You need to add a new one, here, for the Collections class (line 8 below):
When you’ve added the new using statement, you can use the ArrayList. To set up an ArrayList, double click the button on your form to create a code stub. Now add the following line: ArrayList students = new ArrayList();
So you start with the word ArrayList, followed by a space. You then need to come up with a name for your ArrayList. This is just like any variable name, so you can call it almost anything you like. After an equals sign, you type the keyword new, followed by a space. After the space, you type ArrayList(). Notice the round brackets, here.
After setting up the ArrayList, you need to fill it with data. For ArrayLists, it’s better (but not required) to keep to the same data – all text, or all numbers, but not a mix of both. Add the following three lines to your code: students.Add("Jenny"); students.Add("Peter"); students.Add("Mary Jane");
This is a list of all the Methods and Properties that an ArrayList has. The one that you use to add items to your ArrayList is called, not surprisingly, Add( ). Between the round brackets of Add( ), you type the data that you want to add to your ArrayList: students.Add("Jenny"); For every item in your collection, you need a new line that Adds items.
To access the items in your ArrayList, you can use a foreach loop. Add this to your button code: foreach (string child in students) { listBox1.Items.Add( child ); }
So we’re looping round all the items in the ArrayList, and then adding them to the listbox. You can also use an ordinary for loop: for (int i = 0; i < students.Count; i++) { listBox1.Items.Add( students[i] ); }
Notice that the end condition is students.Count. Count is a property of ArrayLists that tells you how many items is in it. Inside the for loop, we’re using square brackets with the index number inside. This is just like the normal arrays you used earlier.
So we’re adding a fourth student to the ArrayList, Azhar, and then displaying the item in the listbox. Add the new code to your button. Run your programme and click your button.
Sorting an ArrayList alphabetically is quite straightforward. You just use the Sort Method. Like this: students.Sort();
To remove an item from your list, you can either use the Remove or the RemoveRange methods. The Remove method deletes single items from the ArrayList. You use it like this: students.Remove("Peter");
In between the round brackets of Remove, you simply type the item you want to remove. If you want to remove more than one item, use RemoveRange. Like this: students.RemoveRange(0, 2);
The first number between the round brackets of RemoveRange is where in your list you want to start. The second number is how many items you want to remove.
Here’s some code to try at the end of your button:
students.RemoveRange(0, 2); listBox1.Items.Add("================="); foreach (string child in students) { listBox1.Items.Add(child); }
But that’s enough of ArrayLists. There’s lots more that you can do with them, and they are worth researching further. The final Collection we’ll look at is called a Hashtable.
You use a Hashtable when you want to store information based on Key/Value pairs. For example, the name of a student AND the score in an exam. This allows you to mix text and numbers. (In other programmes, Hashtables are known as associative arrays.)
Add a new button to your form, and double click it to get at the code. We’ll add code for a Hashtable. You start by setting up the Hashtable:
Hashtable students = new Hashtable(); This creates a new object called students. It’s going to be an Hashtable object.
Like this: students["Jenny"] = 87; students["Peter"] = "No Score"; students["Mary Jane"] = 64; students["Azhar"] = 79;
Or like this: students.Add("Jenny", 87); students.Add("Peter", "No Score";); students.Add("Mary Jane", 64); students.Add("Azhar", 79);
The first method uses a pair of square brackets: students["Jenny"] = 87; In between the square brackets, you type what’s known as the Key. So this particular entry in the Hashtable is called “Jenny”. After an equals sign, you then type the Value that this Key will hold. Notice that three of the entries are number values, and one (Peter) is text.
The second way to store values in a Hashtable is to use the Add Method: students.Add("Jenny", 87); In between the round brackets of Add( ), you first type the Key name. After a comma, you type the Value for that Key.
There is a difference between the two. If you use the Add method, you can’t have duplicate Key names. But you can if you use the square brackets. So this will get you an error: students.Add("Jenny", 87); students.Add("Jenny", 35); But this won’t: students["Jenny"] = 87; students["Jenny"] = 35;
To try Hashtables out for yourself, add the following code to your button: Hashtable students = new Hashtable(); students["Jenny"] = 87; students["Peter"] = "No Score"; students["Mary Jane"] = 64; students["Azhar"] = 79; foreach (DictionaryEntry child in students) { listBox1.Items.Add("student: " + child.Key + " , Score: " + child.Value); }
Before running the code, have a look at the foreach loop. Inside of the round brackets, we have this: DictionaryEntry child This sets up a variable called child. But note the type of variable it is: a DictionaryEntry. C# uses an object of this type when using the foreach loop with Hashtables. That’s because it automatically returns both the Key and the Value.
Notice, too, what we have between the round brackets of the listbox’s Add method:
"student: " + child.Key + " , Score: " + child.Value The bold parts are the important parts. After typing the name of your variable (child, for us) and a full stop, the IntelliSense list will appear. Key is a property that returns the name of your Key, and Value is a property that returns whatever you placed inside of that Key.
Run your programme and click your button. The form on your listbox will then look like this:
Notice that the list of items has been sorted automatically. But the sort is done on the Keys, not on the Values. But just like the ArrayList, you can Add new items, and remove old ones. To Remove an item, you do it like this: students.Remove("Peter"); So you refer to the Key name, and not the Value, when you use the Remove method.
You can create your own collections of things with something called Enumeration. Suppose you wanted to set up a list of subjects that students can study, but don’t want to keep typing the list out all the time. Instead, you can set up an Enumerated list.
Add a new button to the form and set the text property as Enumeration. Double click your button to get at the coding window. Now add the enum part below to your code:
You start with the word enum. After a space, you type a name for your enumerated list. In between a pair of curly brackets, you type the list itself. We’ve added five subjects to our lists;
English, IT, Science, Design, Math.
To use your enumerated list, click inside of your button code. Add the following line:
Subjects newSubject = Subjects.Science;
So you type the name of your enumerated list followed by a space. After coming up with a variable name, type an equals sign. Type the name of your list again, followed by a dot. You will then see the items in your list:
Select one of the items from your list, and end the line with a semicolon. What you have done is to set up your own value type, with its own name (Subjects). The values in your type are the ones you added between the curly brackets. They also have an underlying number. So the first item is 0, the second item is 1, the third 2, etc. To display it in a message box as a string, the code would be this: MessageBox.Show( newSubject.ToString( ) ); It needs converting because it’s an enumerated type – it’s not a string.
If you want to get at the underlying number, you would do the conversion like this:
Subjects newSubject = Subjects.Science; int enumNumber = (int)newSubject;
In other words, convert to int in the usual way, by putting (int) before what it is you want to convert. You could then loop round and do some checking.
Something like this:
for (int i = 0; i < 4; i++) { if (i = = 2) { MessageBox.Show("You're taking Science"); } } Enumerated lists are good for when you have a list of custom items and don’t want to use an array.
Connecting to a Database with C# .NET