.NET 帮助

C# ArrayList(开发者如何使用)

Chipego
奇佩戈-卡琳达
2024年三月6日
分享:

ArrayList 类是 .NET Framework 集合命名空间的一部分,旨在存储对象集合。 它是一个非通用集合,这意味着它可以容纳任何数据类型的项目。 该功能使其具有高度灵活性,但与泛型集合相比,其类型安全性较低。 "(《世界人权宣言》)数组列表该翻译可以包含重复元素,并允许在添加或删除有效值时动态调整大小。 在本文中,我们将讨论 ArrayList 的基础知识和IronPDF 库功能.

ArrayList 的基础知识

数组列表(ArrayList)本质上是一个非通用的集合,能够存储任意数据类型的大量元素,是各种编程场景的通用选择。 其主要特点之一是能够随意添加元素或删除项目,而不受固定大小的限制。 ArrayList 可自动调整大小以容纳新元素,这一功能是通过实现 IList 接口而实现的。 这种动态大小调整对于需要在整个生命周期内具有不同元素数量的集合的应用程序来说至关重要。

当您实例化 ArrayList 时,您创建的集合可以容纳任何对象值,从整数和字符串到复杂的自定义对象。 向ArrayList中添加元素非常简单,这要归功于AddInsert等方法,前者可将对象值添加到集合的末尾,后者可在指定索引处放置新项目,并根据需要移动现有元素以腾出空间。 这种灵活性使开发人员能够更有效地管理集合,并随着应用程序的发展而适应其需求。

使用元素

数组列表中添加元素既简单又直观。例如,您可以考虑建立一个包含各种类型数据的集合。 使用Add方法,您可以向ArrayList追加任何对象,从字符串到整数,甚至其他集合。 ArrayList 的容量会根据需要自动增加,确保始终有空间容纳新的对象 obj 元素。 与需要手动调整大小或创建新数组以容纳更多元素的传统数组相比,这种自动调整大小的功能具有显著优势。

ArrayList 还提供了在特定位置或 int 索引处插入和删除元素的方法。 通过 Insert 方法,您可以在指定位置添加元素,从而有效地将新项目精确地放置在集合中的任意指定索引处。 同样,RemoveRemoveAt方法可通过指定要删除的对象或其在集合中的索引来方便地删除项目。 对 ArrayList 中元素的细粒度控制使其成为管理动态数据的强大工具。

创建和添加元素

要开始使用ArrayList,首先需要创建一个实例。 然后,您可以使用Add方法向ArrayList中添加元素,该方法会将一个对象插入到ArrayList的末尾。

class Program
{
// public static void main
    public static void Main()
    {
        ArrayList myArrayList = new ArrayList();
        myArrayList.Add("Hello");
        myArrayList.Add(100);
        var item = "World";
        myArrayList.Add(item);
        foreach (var obj in myArrayList)
        {
            Console.WriteLine(obj);
        }
    }
}
class Program
{
// public static void main
    public static void Main()
    {
        ArrayList myArrayList = new ArrayList();
        myArrayList.Add("Hello");
        myArrayList.Add(100);
        var item = "World";
        myArrayList.Add(item);
        foreach (var obj in myArrayList)
        {
            Console.WriteLine(obj);
        }
    }
}

C# ArrayList(如何为开发人员工作):图 1 - 创建数组列表输出

本示例演示了如何创建一个新的 ArrayList 并向其中添加不同类型的元素。 然后,foreach循环遍历ArrayList,打印每个元素。

插入元素

要在指定索引处插入元素,请使用 Insert 方法,注意这是一个基于零的索引系统。

myArrayList.Insert(1, "Inserted Item");
myArrayList.Insert(1, "Inserted Item");

删除元素

要删除元素,RemoveRemoveAt 方法就派上用场了。 Remove 删除第一个出现的特定对象,而 RemoveAt 则删除指定整数索引处的元素。

myArrayList.Remove("Hello"); // Removes the first occurrence of "Hello"
myArrayList.RemoveAt(0); // Removes the element at index 0
myArrayList.Remove("Hello"); // Removes the first occurrence of "Hello"
myArrayList.RemoveAt(0); // Removes the element at index 0

示例:管理 ArrayList管理数组列表

在 C# 中创建一个使用ArrayList的高级示例,不仅要展示添加或删除元素等基本操作,还要展示更复杂的操作,如排序、搜索以及将ArrayList转换为其他数据结构。 将以下示例放入 Program.cs 文件中运行:

using System;
using System.Collections;
using System.Linq;
class AdvancedArrayListExample
{
    static void Main(string [] args)
    {
        // Initialize an ArrayList with some elements
        ArrayList numbers = new ArrayList() { 5, 8, 1, 3, 2 };
        // Adding elements
        numbers.Add(6); // Add an element to the end
        numbers.AddRange(new int [] { 7, 9, 0 }); // Add multiple elements from a specified collection.
        Console.WriteLine("Initial ArrayList:");
        foreach (int number in numbers)
        {
            Console.Write(number + " ");
        }
        Console.WriteLine("\n");
        // Removing elements
        numbers.Remove(1); // Remove the element 1
        numbers.RemoveAt(0); // Remove the first element
        Console.WriteLine("After Removal:");
        foreach (int number in numbers)
        {
            Console.Write(number + " ");
        }
        Console.WriteLine("\n");
        // Sorting
        numbers.Sort(); // Sort the ArrayList
        Console.WriteLine("Sorted ArrayList:");
        foreach (int number in numbers)
        {
            Console.Write(number + " ");
        }
        Console.WriteLine("\n");
        // Searching
        int searchFor = 5;
        int index = numbers.IndexOf(searchFor); // Find the index of the element
        if (index != -1)
        {
            Console.WriteLine($"Element {searchFor} found at index {index}");
        }
        else
        {
            Console.WriteLine($"Element {searchFor} not found.");
        }
        Console.WriteLine("\n");
        // Converting ArrayList to Array
        int [] numbersArray = (int [])numbers.ToArray(typeof(int));
        Console.WriteLine("Converted Array:");
        foreach (int number in numbersArray)
        {
            Console.Write(number + " ");
        }
        Console.WriteLine("\n");
        // Demonstrate LINQ with ArrayList (Requires System.Linq)
        var evenNumbers = numbers.Cast<int>().Where(n => n % 2 == 0).ToList(); // Assign values to evenNumbers from the filtered results.
        Console.WriteLine("Even Numbers:");
        evenNumbers.ForEach(n => Console.Write(n + " "));
        Console.WriteLine();
    }
}
using System;
using System.Collections;
using System.Linq;
class AdvancedArrayListExample
{
    static void Main(string [] args)
    {
        // Initialize an ArrayList with some elements
        ArrayList numbers = new ArrayList() { 5, 8, 1, 3, 2 };
        // Adding elements
        numbers.Add(6); // Add an element to the end
        numbers.AddRange(new int [] { 7, 9, 0 }); // Add multiple elements from a specified collection.
        Console.WriteLine("Initial ArrayList:");
        foreach (int number in numbers)
        {
            Console.Write(number + " ");
        }
        Console.WriteLine("\n");
        // Removing elements
        numbers.Remove(1); // Remove the element 1
        numbers.RemoveAt(0); // Remove the first element
        Console.WriteLine("After Removal:");
        foreach (int number in numbers)
        {
            Console.Write(number + " ");
        }
        Console.WriteLine("\n");
        // Sorting
        numbers.Sort(); // Sort the ArrayList
        Console.WriteLine("Sorted ArrayList:");
        foreach (int number in numbers)
        {
            Console.Write(number + " ");
        }
        Console.WriteLine("\n");
        // Searching
        int searchFor = 5;
        int index = numbers.IndexOf(searchFor); // Find the index of the element
        if (index != -1)
        {
            Console.WriteLine($"Element {searchFor} found at index {index}");
        }
        else
        {
            Console.WriteLine($"Element {searchFor} not found.");
        }
        Console.WriteLine("\n");
        // Converting ArrayList to Array
        int [] numbersArray = (int [])numbers.ToArray(typeof(int));
        Console.WriteLine("Converted Array:");
        foreach (int number in numbersArray)
        {
            Console.Write(number + " ");
        }
        Console.WriteLine("\n");
        // Demonstrate LINQ with ArrayList (Requires System.Linq)
        var evenNumbers = numbers.Cast<int>().Where(n => n % 2 == 0).ToList(); // Assign values to evenNumbers from the filtered results.
        Console.WriteLine("Even Numbers:");
        evenNumbers.ForEach(n => Console.Write(n + " "));
        Console.WriteLine();
    }
}

本代码片段演示了如何翻译:

  • 用一组元素初始化数组列表
  • ArrayList 中添加单个和多个元素。
  • 按值和索引删除元素。
  • ArrayList 进行排序,对元素进行排序。
  • 搜索元素并查找其索引。
  • ArrayList 转换为标准数组。
  • 使用 LINQ 和 ArrayList 过滤出偶数,展示如何利用 LINQ 强大的查询功能连接非通用集合。

    C# ArrayList(如何为开发人员工作):图 2 - ArrayList 输出

IronPDF 简介:C# PDF 库

C# ArrayList(如何为开发人员工作):图 3 - IronPDF

IronPDF 是一个功能强大的 C# 库,它简化了复杂的 PDF 生成过程,为 PDF 操作提供了广泛的功能,包括以下能力从HTML生成PDF添加文本和图像、确保文档安全等等。

将 IronPDF 与 ArrayList 相结合

让我们编写一个简单的 C# 程序,创建一个 ArrayList 项目,然后使用 IronPDF 生成一个 PDF 文档,列出这些项目。

using IronPdf;
using System;
using System.Collections;
class pdfocde
{
    static void Main(string [] args)
    {
        IronPdf.License.LicenseKey = "License";
        // Create a new ArrayList and add some items
        ArrayList itemList = new ArrayList();
        itemList.Add("Apple");
        itemList.Add("Banana");
        itemList.Add("Cherry");
        itemList.Add("Date");
        // Initialize a new PDF document
        var Renderer = new ChromePdfRenderer();
        // Create an HTML string to hold our content
        string htmlContent = "<h1>Items List</h1><ul>";
        // Iterate over each item in the ArrayList and add it to the HTML string
        foreach (var item in itemList)
        {
            htmlContent += $"<li>{item}</li>";
        }
        htmlContent += "</ul>";
        // Convert the HTML string to a PDF document
        var PDF = Renderer.RenderHtmlAsPdf(htmlContent);
        // Save the PDF to a file
        PDF.SaveAs("e:\\ItemList.pdf");
        Console.WriteLine("PDF file 'ItemList.pdf' has been generated.");
    }
}
using IronPdf;
using System;
using System.Collections;
class pdfocde
{
    static void Main(string [] args)
    {
        IronPdf.License.LicenseKey = "License";
        // Create a new ArrayList and add some items
        ArrayList itemList = new ArrayList();
        itemList.Add("Apple");
        itemList.Add("Banana");
        itemList.Add("Cherry");
        itemList.Add("Date");
        // Initialize a new PDF document
        var Renderer = new ChromePdfRenderer();
        // Create an HTML string to hold our content
        string htmlContent = "<h1>Items List</h1><ul>";
        // Iterate over each item in the ArrayList and add it to the HTML string
        foreach (var item in itemList)
        {
            htmlContent += $"<li>{item}</li>";
        }
        htmlContent += "</ul>";
        // Convert the HTML string to a PDF document
        var PDF = Renderer.RenderHtmlAsPdf(htmlContent);
        // Save the PDF to a file
        PDF.SaveAs("e:\\ItemList.pdf");
        Console.WriteLine("PDF file 'ItemList.pdf' has been generated.");
    }
}

在本例中,我们首先创建一个名为itemListArrayList,并在其中填充若干字符串项。 接下来,我们初始化一个 IronPDF 的 ChromePdfRenderer 类的新实例,我们将用它来将 HTML 内容转换为 PDF 文档。

输出

以下是 IronPDF 生成的输出 PDF:

C# ArrayList(如何为开发人员工作):图 4 - PDF 输出

结论

C# ArrayList(如何为开发人员工作):图 5 - 许可

ArrayList 是 C# 提供的一个功能强大的集合,用于存储对象列表。 它能够动态调整大小并存储任何类型的元素,因此应用范围广泛。 不过,为了类型安全和更好的性能,建议使用泛型集合。 尝试使用 ArrayList 及其方法将有助于您了解其用途以及如何将其应用到您的应用程序中。

此外,对于那些有兴趣将 C# 功能扩展到 PDF 操作的人,IronPDF 提供了一个免费试用 .NET 中的 PDF 函数以探索其功能。 许可证从 $749 起,为将 PDF 功能集成到 .NET 应用程序中提供了全面的解决方案。

Chipego
软件工程师
Chipego 拥有出色的倾听技巧,这帮助他理解客户问题并提供智能解决方案。他在 2023 年加入 Iron Software 团队,此前他获得了信息技术学士学位。IronPDF 和 IronOCR 是 Chipego 主要专注的两个产品,但他对所有产品的了解每天都在增长,因为他不断找到支持客户的新方法。他喜欢 Iron Software 的合作氛围,公司各地的团队成员贡献他们丰富的经验,以提供有效的创新解决方案。当 Chipego 离开办公桌时,你经常可以发现他在看书或踢足球。
< 前一页
Math.Round C# (它是如何为开发人员工作的)
下一步 >
C# 代码检查工具(开发人员如何使用)