Using ArrayList in C#
This example explains how to insert items into array list and fetch them based on type.
ArrayList is used for dynamic length
Add namespace System.Collections;
Create an Array List
ArrayList arrayList = new ArrayList();
Add items to an array list
arrayList.Add(1);
arrayList.Add(2);
arrayList.Add(3);
arrayList.Add(1.1f);
arrayList.Add(0.5f);
arrayList.Add(2);
arrayList.Add(3);
arrayList.Add(1.1f);
arrayList.Add(0.5f);
arrayList.Add("Hello");
arrayList.Add("World!");
arrayList.Add("World!");
It has integers and float values and string values also/
Get All values from Array List
Console.WriteLine("Display All Values in Array List");
foreach (var item in arrayList)
{
Console.WriteLine(item);
}
Output: 1 2 3 1.1 0.5 Hello World!
foreach (var item in arrayList)
{
Console.WriteLine(item);
}
Output: 1 2 3 1.1 0.5 Hello World!
Get Only Integers from Array List
Console.WriteLine("Get Only Integers");
foreach (var item in arrayList.OfType<int>())
{
Console.Write(item+"\t");
}
foreach (var item in arrayList.OfType<int>())
{
Console.Write(item+"\t");
}
Output:1 2 3
Get Only Float values from Array List
Console.WriteLine("Get Only float");
foreach (var item in arrayList.OfType<float>())
{
Console.Write(item+"\t");
}
foreach (var item in arrayList.OfType<float>())
{
Console.Write(item+"\t");
}
Output:1.1 0.5
Get Only String values from Array List
Console.WriteLine("Get Only String Values");
foreach (var item in arrayList.OfType<string>())
{
Console.Write(item+"\t");
}
foreach (var item in arrayList.OfType<string>())
{
Console.Write(item+"\t");
}
Output:Hello World!
Tags: using ArrayList in C#,C# ArrayList,ArrayList in C#, ArrayList OfType method usage,Insert elements into Array List, Dynamic Array in C#
No comments:
Post a Comment