Add elements to ArrayList
In this chapter you will learn:
- How to add elements to an ArrayList
- How to add array to ArrayList
- Inserting into an ArrayList by index
Adding to ArrayList
The following code adds items to ArrayList and use foreach loop to check.
using System;/*from j av a 2s .c o m*/
using System.Collections;
using System.Collections.Generic;
using System.Text;
class Program {
static void Main(string[] args) {
ArrayList baseballTeams = new ArrayList();
baseballTeams.Add("s");
baseballTeams.Add("r");
baseballTeams.Add("F");
foreach (string item in baseballTeams) {
Console.Write(item + "\n");
}
}
}
Add array to ArrayList
using System;/*from j a v a 2s. co m*/
using System.Collections;
using System.Collections.Generic;
using System.Text;
class Program {
static void Main(string[] args) {
ArrayList baseballTeams = new ArrayList();
baseballTeams.Add("java2s.com");
baseballTeams.Add("r");
baseballTeams.Add("F");
string[] myStringArray = new string[2];
myStringArray[0] = "G";
myStringArray[1] = "L";
baseballTeams.AddRange(myStringArray);
foreach (string item in baseballTeams) {
Console.Write(item + "\n");
}
}
}
Inserting into an ArrayList by index
using System;/*from ja va 2 s.com*/
using System.Collections;
class MainClass {
public static void Main() {
ArrayList al = new ArrayList(5);
// Add three elements to the end of the array
al.Add(10);
al.Add(9);
al.Add(8);
// Now, insert three elements in the front of the array
al.Insert(0, 1);
al.Insert(0, 2);
al.Insert(0, 3);
// Finally, insert into some random spots
al.Insert(2, 4);
al.Insert(4, 5);
al.Insert(6, 6);
// Enumerate the array
foreach (int i in al) {
Console.WriteLine("Entry {0}", i);
}
}
}
Next chapter...
What you will learn in the next chapter:
Home » C# Tutorial » List