You can determine the number of objects in a collection using the collection's Count property:
To write code in Visual Basic
Visual Basic |
Copy Code
|
---|---|
' Set a variable equal to the number of Splits in C1List1. variable = Me.C1List1.Splits.Count |
To write code in C#
C# |
Copy Code
|
---|---|
// Set a variable equal to the number of Splits in C1List1. variable = this.c1List1.Splits.Count; |
You can also iterate through all objects in a collection using the Count property as in the following example, which prints the Caption string of each C1DataColumn object in a list:
To write code in Visual Basic
Visual Basic |
Copy Code
|
---|---|
For n = 0 To Me.C1List1.Columns.Count - 1 Debug.WriteLine(Me.C1List1.Columns(n).Caption) Next n |
To write code in C#
C# |
Copy Code
|
---|---|
for (int n = 0; n <= this.c1List1.Columns.Count - 1; n++) { Console.WriteLine(this.c1List1.Columns[n].Caption); } |
The Count property is also useful for appending and removing columns:
To write code in Visual Basic
Visual Basic |
Copy Code
|
---|---|
' Determine how many columns there are. Dim NumCols As Integer NumCols = Me.C1List1.Columns.Count ' Append a column to the end of the Columns collection. Dim C As New C1List.C1DataColumn() Me.C1List1.Columns.Insert(NumCols, C) ' The following loop removes all columns from the list. While Me.C1List1.Columns.Count Me.C1List1.Columns.RemoveAt(0) End While |
To write code in C#
C# |
Copy Code
|
---|---|
// Determine how many columns there are. int NumCols; NumCols = this.c1List1.Columns.Count; // Append a column to the end of the Columns collection. C1List.C1DataColumn C = new C1List.C1DataColumn(); this.c1List1.Columns.Insert(NumCols, C); // The following loop removes all columns from the list. while (this.c1List1.Columns.Count) this.c1List1.Columns.RemoveAt(0); |
Visual Basic also provides an efficient For Each...Next statement that you can use to iterate through the objects in a collection without using the Count property:
To write code in Visual Basic
Visual Basic |
Copy Code
|
---|---|
Dim C As C1List.C1DataColumn For Each C In Me.C1List1.Columns Debug.WriteLine(C.Caption) Next |
To write code in C#
C# |
Copy Code
|
---|---|
C1List.C1DataColumn C; foreach (C in this.c1List1.Columns ) { Console.WriteLine(C.Caption); } |
In fact, using the For Each...Next statement is the preferred way to iterate through the objects in a collection.