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

Lấy chỉ số lần xuất hiện đầu tiên trong StringCollection C#

Ví dụ 1

Sử dụng phương thức IndexOf để tìm chỉ số đầu tiên của một chuỗi:

using System;
using System.Collections.Specialized;

public class Demo {
    public static void Main() {
        StringCollection strCol = new StringCollection();
        strCol.Add("Accessories");
        strCol.Add("Books");
        strCol.Add("Electronics");
        strCol.Add("Books");
        
        Console.WriteLine("Các phần tử StringCollection...");
        foreach (string res in strCol) {
            Console.WriteLine(res);
        }
        
        strCol.Insert(2, "Headphone");
        
        Console.WriteLine("Các phần tử StringCollection...CẬP NHẬT");
        foreach (string res in strCol) {
            Console.WriteLine(res);
        }
        
        Console.WriteLine("Chỉ số lần xuất hiện đầu tiên của Books? = " + strCol.IndexOf("Books"));
    }
}

Kết quả

Các phần tử StringCollection...
Accessories
Books
Electronics
Books
Các phần tử StringCollection...CẬP NHẬT
Accessories
Books
Headphone
Electronics
Books
Chỉ số lần xuất hiện đầu tiên của Books? = 1

Ví dụ 2

Thêm mảng chuỗi vào StringCollection và tìm chỉ số:

using System;
using System.Collections.Specialized;

public class Demo {
    public static void Main() {
        StringCollection strCol = new StringCollection();
        String[] strArr = new String[] { "A", "B", "C", "D", "E", "F", "D", "H" };
        
        Console.WriteLine("Các phần tử StringCollection...");
        foreach (string str in strArr) {
            Console.WriteLine(str);
        }
        
        strCol.AddRange(strArr);
        
        Console.WriteLine("Phần tử tại chỉ số 5 = " + strCol[5]);
        Console.WriteLine("Số chuỗi trong StringCollection = " + strCol.Count);
        Console.WriteLine("Chỉ số lần xuất hiện đầu tiên của D? = " + strCol.IndexOf("D"));
    }
}

Kết quả

Các phần tử StringCollection...
A
B
C
D
E
F
D
H
Phần tử tại chỉ số 5 = F
Số chuỗi trong StringCollection = 8
Chỉ số lần xuất hiện đầu tiên của D? = 3