C# ArrayList Programs - Lab Manual
Program 1: Creating and Displaying an ArrayList
Aim:
To create an ArrayList, add elements of different types, and display them.
Algorithm:
1. Start the program.
2. Create an ArrayList object.
3. Add integer, string, and float elements into the ArrayList.
4. Use foreach loop to display all elements.
5. End the program.
Program:
using System;
using [Link];
class Program
{
static void Main()
{
ArrayList list = new ArrayList();
[Link](10);
[Link]("Hello");
[Link](3.14);
[Link]("ArrayList Elements:");
foreach (var item in list)
{
[Link](item);
}
}
}
Output:
ArrayList Elements:
10
Hello
3.14
Program 2: Insert and Remove Elements in ArrayList
Aim:
To insert and remove elements from an ArrayList.
Algorithm:
6. Start the program.
7. Create and initialize an ArrayList with some integers.
8. Insert an element at a specific index.
9. Remove an element by value and by index.
10. Display the updated ArrayList.
11. End the program.
Program:
using System;
using [Link];
class Program
{
static void Main()
{
ArrayList list = new ArrayList() { 1, 2, 3, 4, 5 };
[Link](2, 99);
[Link](4);
[Link](0);
[Link]("After Insert & Remove:");
foreach (var item in list)
{
[Link](item);
}
}
}
Output:
After Insert & Remove:
2
99
3
5
Program 3: Sorting and Reversing ArrayList
Aim:
To sort and reverse elements in an ArrayList.
Algorithm:
12. Start the program.
13. Create and initialize an ArrayList with integer values.
14. Sort the ArrayList in ascending order.
15. Reverse the ArrayList.
16. Display both sorted and reversed lists.
17. End the program.
Program:
using System;
using [Link];
class Program
{
static void Main()
{
ArrayList list = new ArrayList() { 40, 10, 30, 20 };
[Link]();
[Link]("Sorted ArrayList:");
foreach (var item in list)
[Link](item);
[Link]();
[Link]("Reversed ArrayList:");
foreach (var item in list)
[Link](item);
}
}
Output:
Sorted ArrayList:
10
20
30
40
Reversed ArrayList:
40
30
20
10
Program 4: Searching in ArrayList
Aim:
To search an element in an ArrayList.
Algorithm:
18. Start the program.
19. Create and initialize an ArrayList with string elements.
20. Check whether a specific element exists using Contains().
21. If found, display the index of that element.
22. Otherwise, display not found message.
23. End the program.
Program:
using System;
using [Link];
class Program
{
static void Main()
{
ArrayList list = new ArrayList() { "apple", "banana", "cherry" };
if ([Link]("banana"))
{
[Link]("Banana is found at index: " + [Link]("banana"));
}
else
{
[Link]("Banana not found");
}
}
}
Output:
Banana is found at index: 1