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

Thêm đối tượng vào cuối Collection trong C#

Ví dụ 1

Sử dụng phương thức Add của Collection<T>:

using System;
using System.Collections.ObjectModel;

public class Demo {
    public static void Main() {
        Collection<int> col = new Collection<int>();
        col.Add(10);
        col.Add(20);
        col.Add(30);
        col.Add(40);
        col.Add(50);
        col.Add(60);
        col.Add(70);
        col.Add(80);
        
        Console.WriteLine("Các phần tử Collection...");
        foreach(int val in col) {
            Console.WriteLine(val);
        }
        
        Console.WriteLine("Có phần tử 70? = " + col.Contains(70));
        Console.WriteLine("Số phần tử = " + col.Count);
    }
}

Kết quả

Các phần tử Collection...
10
20
30
40
50
60
70
80
Có phần tử 70? = True
Số phần tử = 8

Ví dụ 2: Thêm thêm phần tử

using System;
using System.Collections.ObjectModel;

public class Demo {
    public static void Main() {
        Collection<int> col = new Collection<int>();
        col.Add(10);
        col.Add(20);
        col.Add(30);
        col.Add(40);
        col.Add(50);
        col.Add(60);
        col.Add(70);
        col.Add(80);
        
        Console.WriteLine("Các phần tử Collection...");
        foreach(int val in col) {
            Console.WriteLine(val);
        }
        
        Console.WriteLine("Số phần tử = " + col.Count);
        
        col.Add(100);
        col.Add(150);
        col.Add(200);
        
        Console.WriteLine("Các phần tử Collection...CẬP NHẬT");
        foreach(int val in col) {
            Console.WriteLine(val);
        }
        
        Console.WriteLine("Số phần tử...CẬP NHẬT = " + col.Count);
    }
}

Kết quả

Các phần tử Collection...
10
20
30
40
50
60
70
80
Số phần tử = 8
Các phần tử Collection...CẬP NHẬT
10
20
30
40
50
60
70
80
100
150
200
Số phần tử...CẬP NHẬT = 11