温馨提示×

c# arraylist能进行查找元素吗

c#
小樊
88
2024-11-15 23:46:14
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

是的,C#中的ArrayList类可以进行元素查找。你可以使用IndexOf方法来查找特定元素在ArrayList中的索引位置。以下是一个示例:

using System;
using System.Collections.ArrayList;

class Program
{
    static void Main()
    {
        ArrayList myList = new ArrayList();
        myList.Add("Apple");
        myList.Add("Banana");
        myList.Add("Cherry");

        string itemToFind = "Banana";
        int index = myList.IndexOf(itemToFind);

        if (index != -1)
        {
            Console.WriteLine($"Element '{itemToFind}' found at index {index}.");
        }
        else
        {
            Console.WriteLine($"Element '{itemToFind}' not found.");
        }
    }
}

在这个示例中,我们创建了一个包含三个元素的ArrayList,然后使用IndexOf方法查找字符串"Banana"的索引位置。如果找到了该元素,IndexOf方法将返回其索引值,否则返回-1。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:c# arraylist有哪些使用技巧

0