Sie sind auf Seite 1von 18

ArrayList: Dynamic array in .

NET
by: juliet

ArrayList: Dynamic array in .NET

by:

This simple tutorial teaches you how to work with an ArrayList class. Many people who
switches from the C/C++ world found that there is no dynamic memory allocation in
the arrays of C#. Actually there is a class in .NET which allows you to do the same
functionality as dynamic memory allocation but is much simpler to use - the ArrayList
class. With ArrayList, you no longer need to worry about freeing up memory after
allocation of memory and array bound overflow.

Here is the code to build an ArrayList, and retrieve content from it:
using System;
using System.Collections;

class TestArrayList {
public static void Main() {
ArrayList myList = new ArrayList();
int i;

for(i=0; i<5; i++)


myList.Add(i);

myList.Add("Hello");

for(i=0; iConsole.WriteLine("Array Index [{0}]: {1}", i,


myList[i].ToString());
}
}

To use it, you must "using" the System.Collections namespace since the ArrayList class
is defined in it. The Add() method of the ArrayList accept an Object instance as its
argument, therefore, as you can see, you can put into it an integer or a string alike, or any
user-defined class.

In the second for loop, you would see I had used the Count property of the ArrayList
class to retrieve the number of element in it. It is very convenient since you do not have
to book keep the number of element in this array. Finally, remember when you print the
content of the ArrayList to the screen, you have to use the ToString() method of the
element, since retrieval of an myList[i] element would return an Object type.

VB.NET ArrayList Examples


You want to use the ArrayList type in the VB.NET programming language. Although
an array type may offer superior performance, the ArrayList can be expanded
automatically by built-in code, making a dynamic array. Here, we describe the
ArrayList type in the VB.NET language, which is one of the easiest and more useful
data types.
Using Add
First, the Add method on the VB.NET ArrayList instance type is very commonly used.
The Add method appends the object argument to the very end of the internal
ArrayList data structure. You do not need to check to see if there is room before
adding the element; there will always be room except in extreme circumstances such
as out-of-memory situations. This program adds three elements to the ArrayList.
--- Program that uses ArrayList and Add (VB.NET) ---

Module Module1

Sub Main()

' Create a new ArrayList.

' ... Then add three strings to it.

Dim list As New ArrayList

list.Add("One")

list.Add("Two")

list.Add("Three")

End Sub

End Module

Using parameter
Here, we describe how it is possible and often useful to receive an ArrayList type as a
parameter to a method Sub. This enables you to exploit structured programming with
the ArrayList type to a larger extent. The Example method here could be used with
any ArrayList instance, with any elements in its internal storage.
--- Program that uses ArrayList with method (VB.NET) ---

Module Module1

Sub Main()

' Create an ArrayList and add two elements to it.

Dim list As New ArrayList

list.Add(5)

list.Add(7)

' Use ArrayList as an argument to the method.

Example(list)

End Sub

''' <summary>

''' Receives ArrayList as argument.

''' </summary>

Private Sub Example(ByVal list As ArrayList)

Dim num As Integer

For Each num In list

Console.WriteLine(num)

Next
End Sub

End Module

--- Output of the program ---

Using AddRange
It is possible to add a range of elements from one ArrayList onto the end of another
ArrayList. To do this, please consider using the AddRange method. The AddRange
method receives one argument, which is an ArrayList type that contains elements
you want to add to the end of the instance ArrayList you call the method on. In this
example, the two array lists are effectively concatenated.
--- Program that uses AddRange method (VB.NET) ---

Module Module1

Sub Main()

' Create an ArrayList and add two elements.

Dim list1 As New ArrayList

list1.Add(5)

list1.Add(7)

' Create a separate ArrayList.

Dim list2 As New ArrayList

list2.Add(10)

list2.Add(13)

' Add this ArrayList to the other one.

list1.AddRange(list2)

' Loop over the elements.

Dim num As Integer

For Each num In list1

Console.WriteLine(num)

Next

End Sub

End Module

--- Output of the program ---

10

13

Using Count and Clear


Often when programming with the ArrayList type, you will not be sure how many
elements are in the current instance. Fortunately, the ArrayList offers the Count
instance property. This property quickly returns the number of elements in the
ArrayList. Also, this example demonstrates the Clear method. After you call the Clear
method, the Count property will return zero elements: this is because all of the
elements were removed.
--- Program that uses ArrayList and Count property (VB.NET) ---

Module Module1

Sub Main()
' Add two elements to the ArrayList.

Dim list As New ArrayList

list.Add(9)

list.Add(10)

' Write the Count.

Console.WriteLine(list.Count)

' Clear the ArrayList.

list.Clear()

' Write the Count again.

Console.WriteLine(list.Count)

End Sub

End Module

--- Output of the program ---

Adding and removing elements


In this section, we demonstrate how you can use the Add, RemoveAt, Insert, and
RemoveRange methods on the ArrayList type in the VB.NET programming language.
We have already seen the Add method in the first example in this article. Next, we
see how the RemoveAt method works: it receives an index argument, which
corresponds to the element index you want to remove. The Insert method receives
two arguments: the position you want to insert at, and the object reference itself.
Finally, the RemoveRange methods receives two arguments: the index you want to
start removing at, and the number of elements you want to remove.
--- Program that uses Add, RemoveAt, Insert, RemoveRange (VB.NET) ---

Module Module1

Sub Main()

' Create an ArrayList and add three strings to it.

Dim list As New ArrayList

list.Add("Dot")

list.Add("Net")

list.Add("Perls")

' Remove a string.

list.RemoveAt(1)

' Insert a string.

list.Insert(0, "Carrot")

' Remove a range.

list.RemoveRange(0, 2)

' Display.

Dim str As String

For Each str In list

Console.WriteLine(str)

Next

End Sub

End Module

--- Output of the program ---

Perls
Using TryCast
In the ArrayList type, elements are not stored with a type directly; instead they are
accessed through the object base type. To cast an object to the more derived type
you want to use, please use the TryCast operator. The syntax for this operator
receives two arguments: the element you want to cast from the ArrayList, and then
the type to which you want to cast. The TryCast operator will not throw exceptions,
as it uses the tester-doer pattern.
--- Program that uses ArrayList and TryCast (VB.NET) ---

Module Module1

Sub Main()

' Create a new ArrayList.

Dim list As New ArrayList

list.Add("man")

list.Add("woman")

list.Add("plant")

' Loop over the ArrayList with a For loop.

Dim i As Integer

For i = 0 To list.Count - 1

' Cast to a string.

Dim str As String = TryCast(list.Item(i), String)

Console.WriteLine(str)

Next i

End Sub

End Module

--- Output of the program ---

man

woman

plant

Using GetRange
In this example, we look at how you can programmatically extract one part of an
ArrayList instance into another ArrayList instance. To do this, please use the
GetRange instance method on the original ArrayList instance. Then, assign the result
of the GetRange method call to a new ArrayList variable reference. The GetRange
uses the standard pattern for range-based methods: it receives the starting index
from which you want to copy, and then the count of elements you want to get.
--- Program that uses ArrayList and GetRange (VB.NET) ---

Module Module1

Sub Main()

' Create new ArrayList.

Dim list1 As New ArrayList

list1.Add("fish")

list1.Add("amphibian")

list1.Add("bird")

list1.Add("plant")

' Create a new ArrayList and fill it with the range from the first
one.

Dim list2 As New ArrayList

list2 = list1.GetRange(2, 2)

' Loop over the elements.


Dim str As String

For Each str In list2

Console.WriteLine(str)

Next

End Sub

End Module

--- Output of the program ---

bird

plant

Use array and ArrayList (VB.net)

<%@ Page Language="VB" %>


<script runat="server">
Dim ColorList(6) as String
Dim FontList as new ArrayList()

Sub Page_Load
' Add the colors to the array
ColorList(0) = "Red"
ColorList(1) = "Orange"
ColorList(2) = "Yellow"
ColorList(3) = "Green"
ColorList(4) = "Blue"
ColorList(5) = "Indigo"
ColorList(6) = "Violet"

FontList.Add("Times New Roman")


FontList.Add("Arial")
FontList.Add("Verdana")
FontList.Add("Comic Sans MS")

If Not Page.IsPostback
Dim ColorName as String

For Each ColorName in ColorList


ddlColorList.Items.Add(ColorName)
Next

ddlFontList.DataSource = FontList
ddlFontList.DataBind()

End If
End Sub

Sub btnSelectColor_Click(sender As Object, e As EventArgs)


lblOutputMessage.Text = "You selected " & _
ddlColorList.SelectedItem.Value & " text written in " & _
ddlFontList.SelectedItem.Value
lblOutputMessage.ForeColor = _
System.Drawing.Color.FromName(ddlColorList.SelectedItem.Text)
lblOutputMessage.Font.Name = _
ddlFontList.SelectedItem.Text

End Sub

</script>
<html>
<head>
</head>
<body>
<form runat="server">
<p>
Select a color from the list:<asp:DropDownList id="ddlColorList" runat="ser
</p>
<p>
Then select a font sytle from the list:
<asp:DropDownList id="ddlFontList" runat="server"></asp:DropDownList>
</p>
<p>
&nbsp;<asp:Button id="btnSelectColor" onclick="btnSelectColor_Click" runat=
</p>
<p>
<asp:Label id="lblOutputMessage" runat="server"></asp:Label>
</p>
</form>
</body>
</html>

ArrayList is one of the most flixible data structure from VB.NET


Collections. ArrayList contains a simple list of values. Very easily we can
add , insert , delete , view etc.. to do with ArrayList. It is very flexible becuse
we can add without any size information , that is it grow dynamically and also
shrink .
Important functions in ArrayList
Add : Add an Item in an ArrayList
Insert : Insert an Item in a specified position in an ArrayList
Remove : Remove an Item from ArrayList
RemoveAt: remeove an item from a specified position
Sort : Sort Items in an ArrayList
How to add an Item in an ArrayList ?
Syntax : ArrayList.add(Item)
Item : The Item to be add the ArrayList
Dim ItemList As New ArrayList()
ItemList.Add("Item4")
How to Insert an Item in an ArrayList ?
Syntax : ArrayList.insert(index,item)
index : The position of the item in an ArrayList
Item : The Item to be add the ArrayList
ItemList.Insert(3, "item6")
How to remove an item from arrayList ?
Syntax : ArrayList.Remove(item)
Item : The Item to be add the ArrayList
ItemList.Remove("item2")
How to remove an item in a specified position from an ArrayList ?
Syntax : ArrayList.RemoveAt(index)
index : the position of an item to remove from an ArrayList
ItemList.RemoveAt(2)
How to sort ArrayList ?
Syntax : ArrayListSort()
The following VB.NET source code shows some function in ArrayList

VB.NET Source Code Download Print Source Code


How to VB.NET ArrayList - Download

VB.Net Tutorial

Public Class Form1


Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
Dim i As Integer
Dim ItemList As New ArrayList()
ItemList.Add("Item4")
ItemList.Add("Item5")
ItemList.Add("Item2")
ItemList.Add("Item1")
ItemList.Add("Item3")
MsgBox("Shows Added Items")
For i = 0 To ItemList.Count - 1
MsgBox(ItemList.Item(i))
Next
'insert an item
ItemList.Insert(3, "Item6")
'sort itemms in an arraylist
ItemList.Sort()
'remove an item
ItemList.Remove("Item1")
'remove item from a specified index
ItemList.RemoveAt(3)
MsgBox("Shows final Items the ArrayList")
For i = 0 To ItemList.Count - 1
MsgBox(ItemList.Item(i))
Next
End Sub
End Class

When you execute this program , at first add five items in the arraylist and
displays. Then again one more item inserted in the third position , and then sort
all items. Next it remove the item1 and also remove the item in the third
position . Finally it shows the existing items.

Work with VB.NET's ArrayList methods and properties

By Irina Medvinskaya, TechRepublic | 2006/10/16 10:46:02

Tags: .net, arraylist, vb

Change the text size: a | A

• Print this

• E-mail this

• Leave a comment

• Clip this


Close
The ability to use collections is important in any language and practical for any application. Collections allow you to manage groups of objects.

In this article, I'll look at how to use an ArrayList class, which provides basic functionality that is useful to most applications. I'll also cover the basics about the methods
within the class.

An ArrayList class
An ArrayList class represents a dynamically sized, index-based collection of objects. In the cases where you don't know the number of objects that you would store, an
ArrayList class is a good option to utilize.

The System.Collections.ArrayList class provides general collection functionality that is suitable for many uses. The class allows you to dynamically add and remove items
from a list. Items are accessed by using an index of the item.

The following example shows how to create a new instance of an ArrayListclass:

Dim arrayListInfo As New System.Collections.ArrayList()


The Add method
Once instantiated, you can add items to an ArrayList class using the Add method. For example, the following code shows how to add items to an existing ArrayList class:

Dim arrayListInfo As New ArrayList()


ArrayListInfo.Add("Item1")
arrayListInfo.Add("Item2")
arrayListInfo.Add("Item3")
An ArrayList class is a zero-based collection; therefore, the first object added to the list is assigned the index zero, and all subsequent objects are assigned to the next
available index.

The Item property indexer


The Item property of an ArrayList class gets or sets the element at the specified index. You can retrieve an item from an ArrayList class at a particular index by using the
Item property.

This is the default property for collections in VB.NET. This means you can access it without using the Item property name, allowing syntax similar to that of an array.

The following example shows how to retrieve a reference to an object in a collection:

Dim objItem As Object


objItem = arrayListInfo(0)
or
Dim objItem As Object
objItem = arrayListInfo.Item(0)
The Remove and RemoveAt methods
In order to remove an item from a collection, you can utilize either the Remove or RemoveAt method. The Remove method requires a reference to an object contained
within the collection as a parameter and removes that object from the collection. The RemoveAtmethod allows you to remove an object at a particular index.

As items are removed from a collection, the index numbers are reassigned to occupy any available spaces; so, index values are not static and might not always return the
same reference.

The Count property


The Count property returns the current number of items in a collection. The collections are always zero-based; therefore, the Count property will always return a value that
is one greater than the upper bound of the array.

Stack is one of another easy to use VB.NET Collections .


Stack follows the push-pop operations. That is we can Push
Items into Stack and Pop it later . And It follows the Last In
First Out (LIFO) system. That is we can push the items into a
stack and get it in reverse order. Stack returns the last item
first.
Commonly used methods :
Push : Add (Push) an item in the stack datastructure
Syntax : Stack.Push(Object)
Object : The item to be inserted.
Pop : Pop return the item last Item to insert in stack
Syntax : Stack.Pop()
Return : The last object in the Stack
Contains : Check the object contains in the stack
Syntax : Stack.Contains(Object)
Object : The specified Object to be seach
The following VB.NET Source code shows some of
commonly used functions :
VB.NET Source Code Download Print Source Code
How to VB.Net Stack - Download

VB.Net Tutorial

Public Class Form1


Private Sub Button1_Click(ByVal sender As
System.Object,
ByVal e As System.EventArgs) Handles
Button1.Click
Dim stackTable As New Stack
stackTable.Push("Sun")
stackTable.Push("Mon")
stackTable.Push("Tue")
stackTable.Push("Wed")
stackTable.Push("Thu")
stackTable.Push("Fri")
stackTable.Push("Sat")
If stackTable.Contains("Wed") Then
MsgBox(stackTable.Pop())
Else
MsgBox("not exist")
End If
End Sub
End Class

When you execute this program add seven items in the stack .
Then its checks the item "Wed" exist in the Stack. If the item
exist in the Stack , it Pop the last item from Stack , else it
shows the msg "Not Exist"

HashTable stores a Key Value pair type collection of data . We can retrive
items from hashTable to provide the key . Both key and value are Objects.
The common functions using in Hashtable are :
Add : To add a pair of value in HashTable
Syntax : HashTable.Add(Key,Value)
Key : The Key value
Value : The value of corrosponding key
ContainsKey : Check if a specified key exist or not
Synatx : HashTable.ContainsKey(key)
Key : The Key value for search in HahTable
ContainsValue : Check the specified Value exist in HashTable
Synatx : HashTable.ContainsValue(Value)
Value : Search the specified Value in HashTable
Remove : Remove the specified Key and corrosponding Value
Syntax : HashTable.Remove(Key)
Key : The argument key of deleting pairs
The following source code shows all important operations in a HashTable

VB.NET Source Code Download Print Source Code


How to VB.Net HashTable - Download

VB.Net Tutorial

Public Class Form1


Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
Dim weeks As New Hashtable
Dim day As DictionaryEntry
weeks.Add("1", "Sun")
weeks.Add("2", "Mon")
weeks.Add("3", "Tue")
weeks.Add("4", "Wed")
weeks.Add("5", "Thu")
weeks.Add("6", "Fri")
weeks.Add("7", "Sat")
'Display a single Item
MsgBox(weeks.Item("5"))
'Search an Item
If weeks.ContainsValue("Tue") Then
MsgBox("Find")
Else
MsgBox("Not find")
End If
'remove an Item
weeks.Remove("3")
'Display all key value pairs
For Each day In weeks
MsgBox(day.Key " -- " day.Value)
Next
End Sub
End Class
Arrays are using for store similar data types grouping as a single unit. We
can access Array elements by its numeric index.
Dim week(6) As String
The above Vb.Net statements means that , an Array named as week declared
as a String type and it can have the capability of seven String type values.
week(0) = "Sunday"
week(1) = "Monday"
In the above statement , we initialize the values to the String Array. week(0)
= "Sunday" means , we initialize the first value of Array as "Sunday" ,
Dim weekName as String = week(1)
We can access the Arrays elements by providing its numerical index, the
above statement we access the second value from the week Array.
In the following program , we declare an Array "week" capability of seven
String values and assigns the seven values as days in a week . Next step is to
retrieve the elements of the Array using a For loop. For finding the end of an
Array we used the Length function of Array Object.

VB.NET Source Code Download Print Source Code


How to VB.Net Arrays - Download

VB.Net Tutorial

Public Class Form1


Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim i As Integer
Dim week(6) As String
week(0) = "Sunday"
week(1) = "Monday"
week(2) = "Tuesday"
week(3) = "Wednesday"
week(4) = "Thursday"
week(5) = "Friday"
week(6) = "Saturday"

For i = 0 To week.Length - 1
MsgBox(week(i))
Next
End Sub
End Class

The Queue is another adtastructure from VB.NET Collections . It works like


FIFO system. That is First In First Out, The item added in Queue is , first get
out from Queue. We can Enqueue (add) items in Queue and we can Dequeue
(remove from Queue ) or we can Peek (that is get the reference of first item
added in Queue ) the item from Queue.
The commonly using functions are follows :
Enqueue : Add an Item in Queue
Syntax : Stack.Enqueue(Object)
Object : The item to add in Queue
Dequeue : Remove the oldest item from Queue (we dont get the item
later)
Syntax : Stack.Dequeue()
Returns : Remove the oldest item and return.
Peek : Get the reference of the oldest item (it is not removed
permenantly)
Syntax : Stack.Peek()
returns : Get the reference of the oldest item in the Queue
The following VB.NET Source code shows some of commonly used
functions :

VB.NET Source Code Download Print Source Code


How to VB.Net Queue - Download

VB.Net Tutorial

Public Class Form1


Private Sub Button1_Click(ByVal sender As System.Object,_
ByVal e As System.EventArgs) Handles Button1.Click
Dim queueList As New Queue
queueList.Enqueue("Sun")
queueList.Enqueue("Mon")
queueList.Enqueue("Tue")
queueList.Enqueue("Wed")
queueList.Enqueue("Thu")
queueList.Enqueue("fri")
queueList.Enqueue("Sat")
MsgBox(queueList.Dequeue())
MsgBox(queueList.Peek())
If queueList.Contains("Sun") Then
MsgBox("Contains Sun ")
Else
MsgBox("Not Contains Sun ")
End If
End Sub
End Class

When you execute the program it add seven items in the Queue. Then it
Dequeue (remove) the oldest item from queue. Next it Peek() the oldest item
from Queue (shows only , not remove ). Next it check the Item "Sun"
contains in the Queue.

The Queue is another adtastructure from VB.NET Collections . It works like


FIFO system. That is First In First Out, The item added in Queue is , first get
out from Queue. We can Enqueue (add) items in Queue and we can Dequeue
(remove from Queue ) or we can Peek (that is get the reference of first item
added in Queue ) the item from Queue.
The commonly using functions are follows :
Enqueue : Add an Item in Queue
Syntax : Stack.Enqueue(Object)
Object : The item to add in Queue
Dequeue : Remove the oldest item from Queue (we dont get the item
later)
Syntax : Stack.Dequeue()
Returns : Remove the oldest item and return.
Peek : Get the reference of the oldest item (it is not removed
permenantly)
Syntax : Stack.Peek()
returns : Get the reference of the oldest item in the Queue
The following VB.NET Source code shows some of commonly used
functions :
VB.NET Source Code Download Print Source Code
How to VB.Net Queue - Download

VB.Net Tutorial

Public Class Form1


Private Sub Button1_Click(ByVal sender As System.Object,_
ByVal e As System.EventArgs) Handles Button1.Click
Dim queueList As New Queue
queueList.Enqueue("Sun")
queueList.Enqueue("Mon")
queueList.Enqueue("Tue")
queueList.Enqueue("Wed")
queueList.Enqueue("Thu")
queueList.Enqueue("fri")
queueList.Enqueue("Sat")
MsgBox(queueList.Dequeue())
MsgBox(queueList.Peek())
If queueList.Contains("Sun") Then
MsgBox("Contains Sun ")
Else
MsgBox("Not Contains Sun ")
End If
End Sub
End Class

When you execute the program it add seven items in the Queue. Then it
Dequeue (remove) the oldest item from queue. Next it Peek() the oldest item
from Queue (shows only , not remove ). Next it check the Item "Sun"
contains in the Queue.

Dynamic Arrays can resize the capability of the Array at runtime .when you
are in a situation that you do not know exactly the number of elements to
store in array while you making the program. In that situations we are using
Dynamic Array .
Initial declaration
Dim scores() As Integer
Resizing
ReDim scores(1)
If you want to keep the existing items in the Array , you can use the keyword
Preserve .
ReDim Preserve scores(2)
In this case the Array dynamically allocate one more String value and keep
the existing values.

VB.NET Source Code Download Print Source Code


How to VB.Net Dyanamic Array - Download

VB.Net Tutorial

Public Class Form1


Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim i As Integer
Dim scores() As Integer

ReDim scores(1)
scores(0) = 100
scores(1) = 200

For i = 0 To scores.Length - 1
MsgBox(scores(i))
Next

ReDim Preserve scores(2)

scores(2) = 300

For i = 0 To scores.Length - 1
MsgBox(scores(i))
Next
End Sub
End Class

NameValueCollection is used to store data like Name, Value format. It is


very similar to Vb.Net HashTable, HashTable also stores data in Key , value
format . NameValueCollection can hold more than one value for a
corresponding Key.
Adding new pairs
Add(ByVal name As String, ByVal value As String)
Add("High","80")
Get the value of corresponding Key
GetValues(ByVal name As String) As String()
String values() = GetValues("High")
VB.NET Source Code Download Print Source Code
How to VB.Net NameValueCollection - Download

VB.Net Tutorial

Imports System.Collections.Specialized
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click

Dim markStatus As New NameValueCollection


Dim key As String
Dim values() As String

markStatus.Add("Very High", "80")


markStatus.Add("High", "60")
markStatus.Add("medium", "50")
markStatus.Add("Pass", "40")

For Each key In markStatus.Keys


values = markStatus.GetValues(key)
For Each value As String In values
MsgBox(key & " - " & value)
Next value
Next key

End Sub
End Class

Das könnte Ihnen auch gefallen