Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Thêm phần tử vào cuối ArrayList trong C#

Giới thiệu

ArrayList (namespace System.Collections) là mảng động kích thước tự điều chỉnh. Phương thức Add(object) thêm một phần tử vào cuối; AddRange(ICollection) thêm nhiều phần tử từ một tập hợp khác.

Ví dụ 1: Add và AddRange

using System;
using System.Collections;

public class Demo
{
    public static void Main(string[] args)
    {
        ArrayList list = new ArrayList();
        list.Add("Andy");
        list.Add("Gary");
        list.Add("Katie");
        list.Add("Amy");

        Console.WriteLine("Các phần tử trong ArrayList...");
        foreach (string res in list)
        {
            Console.WriteLine(res);
        }

        string[] strArr = { "John", "Jacob" };
        list.AddRange(strArr);

        Console.WriteLine("Các phần tử trong ArrayList...CẬP NHẬT");
        foreach (string str in list)
        {
            Console.WriteLine(str);
        }
    }
}

Kết quả

Các phần tử trong ArrayList...
Andy
Gary
Katie
Amy
Các phần tử trong ArrayList...CẬP NHẬT
Andy
Gary
Katie
Amy
John
Jacob

Ví dụ 2: Thêm nhiều lần với AddRange

using System;
using System.Collections;

public class Demo
{
    public static void Main(string[] args)
    {
        ArrayList list = new ArrayList();
        list.Add("Andy");
        list.Add("Gary");
        list.Add("Katie");
        list.Add("Amy");

        Console.WriteLine("Các phần tử trong ArrayList...");
        foreach (string res in list)
        {
            Console.WriteLine(res);
        }

        string[] strArr = { "John", "Jacob" };
        list.AddRange(strArr);
        Console.WriteLine("Các phần tử trong ArrayList...CẬP NHẬT");
        foreach (string str in list)
        {
            Console.WriteLine(str);
        }

        string[] strArr2 = { "Tim", "Tom", "David" };
        list.AddRange(strArr2);
        Console.WriteLine("Các phần tử trong ArrayList...CẬP NHẬT");
        foreach (string str in list)
        {
            Console.WriteLine(str);
        }
    }
}

Kết quả

Các phần tử trong ArrayList...
Andy
Gary
Katie
Amy
Các phần tử trong ArrayList...CẬP NHẬT
Andy
Gary
Katie
Amy
John
Jacob
Các phần tử trong ArrayList...CẬP NHẬT
Andy
Gary
Katie
Amy
John
Jacob
Tim
Tom
David

Lưu ý

  • ArrayList lưu trữ object, nên có boxing/unboxing với kiểu giá trị (int, double...).
  • Ưu tiên dùng List<T> (generic) cho type safety và hiệu suất tốt hơn.
  • Capacity tự động tăng gấp đôi khi cần.