Arrays C# Console Foreach Statement

C# Arraylist Examples

It represents an ordered collection of an object that can be indexed individually. It is basically an alternative to an array.

For arrays, you need to define the number of elements that the array can hold at the time of array declaration. But in the case of the Array List collection, this does not need to be done beforehand. Elements can be added or removed from the Array List collection at any point in time. Let’s look at the operations available for the array list collection in more detail.

Properties of ArrayList Class

Capacity :Ā Gets or sets the number of elements that the ArrayList can contain.

Count :Ā Gets the number of elements actually contained in the ArrayList.

IsFixedSize :Ā Gets a value indicating whether the ArrayList has a fixed size.

IsReadOnly :Ā Gets a value indicating whether the ArrayList is read-only.

Item :Ā Gets or sets the element at the specified index.

 

Methods of ArrayList Class

Add:Ā Adds an object to the end of the ArrayList.

AddRange:Ā Adds the elements of an ICollection to the end of the ArrayList.

Clear:Ā Removes all elements from the ArrayList.

Contains:Ā Determines whether an element is in the ArrayList.

GetRange:Ā Returns an ArrayList which represents a subset of the elements in the source ArrayList.

IndexOf:Ā Returns the zero-based index of the first occurrence of a value in the ArrayList or in a portion of it.

Insert:Ā Inserts an element into the ArrayList at the specified index.

InsertRange:Ā Inserts the elements of a collection into the ArrayList at the specified index.

Remove:Ā Removes the first occurrence of a specific object from the ArrayList.

RemoveAt:Ā Removes the element at the specified index of the ArrayList.

RemoveRange:Ā Removes a range of elements from the ArrayList.

Reverse:Ā Reverses the order of the elements in the ArrayList.

SetRange:Ā Copies the elements of a collection over a range of elements in the ArrayList.

Sort:Ā Sorts the elements in the ArrayList.

TrimToSize:Ā Sets the capacity to the actual number of elements in the ArrayList.

Declaration of an Array List

The declaration of an ArrayList is provided below. An array list is created with the help of the ArrayList Data type. The “new” keyword is used to create an object of an ArrayList.

Adding elements to an ArrayList

Display the elements of the ArrayList.

Output:

Print an ArrayList with a for-each loop

Output:

csharp
console
examples

 

Count:

Output:Ā 

3

 

Contains:

Output:

false

 

RemoveAt:

Output:

csharp
examples

 

Sort:

Output:

console
csharp
examples

 

Reverse:

Output:

examples
console
csharp

 

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.