.NET 帮助

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

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

ArrayList 的基础知识

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

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

使用元素

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

ArrayList 还提供了在特定位置或整数索引处插入和删除元素的方法。 通过 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);
        }
    }
}
Friend Class Program
' public static void main
	Public Shared Sub Main()
		Dim myArrayList As New ArrayList()
		myArrayList.Add("Hello")
		myArrayList.Add(100)
		Dim item = "World"
		myArrayList.Add(item)
		For Each obj In myArrayList
			Console.WriteLine(obj)
		Next obj
	End Sub
End Class
$vbLabelText   $csharpLabel

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

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

插入元素

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

myArrayList.Insert(1, "Inserted Item");
myArrayList.Insert(1, "Inserted Item");
myArrayList.Insert(1, "Inserted Item")
$vbLabelText   $csharpLabel

删除元素

要删除元素,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
myArrayList.Remove("Hello") ' Removes the first occurrence of "Hello"
myArrayList.RemoveAt(0) ' Removes the element at index 0
$vbLabelText   $csharpLabel

示例:管理 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();
    }
}
Imports Microsoft.VisualBasic
Imports System
Imports System.Collections
Imports System.Linq
Friend Class AdvancedArrayListExample
	Shared Sub Main(ByVal args() As String)
		' Initialize an ArrayList with some elements
		Dim numbers As New ArrayList() From { 5, 8, 1, 3, 2 }
		' Adding elements
		numbers.Add(6) ' Add an element to the end
		numbers.AddRange(New Integer () { 7, 9, 0 }) ' Add multiple elements from a specified collection.
		Console.WriteLine("Initial ArrayList:")
		For Each number As Integer In numbers
			Console.Write(number & " ")
		Next number
		Console.WriteLine(vbLf)
		' Removing elements
		numbers.Remove(1) ' Remove the element 1
		numbers.RemoveAt(0) ' Remove the first element
		Console.WriteLine("After Removal:")
		For Each number As Integer In numbers
			Console.Write(number & " ")
		Next number
		Console.WriteLine(vbLf)
		' Sorting
		numbers.Sort() ' Sort the ArrayList
		Console.WriteLine("Sorted ArrayList:")
		For Each number As Integer In numbers
			Console.Write(number & " ")
		Next number
		Console.WriteLine(vbLf)
		' Searching
		Dim searchFor As Integer = 5
		Dim index As Integer = numbers.IndexOf(searchFor) ' Find the index of the element
		If index <> -1 Then
			Console.WriteLine($"Element {searchFor} found at index {index}")
		Else
			Console.WriteLine($"Element {searchFor} not found.")
		End If
		Console.WriteLine(vbLf)
		' Converting ArrayList to Array
		Dim numbersArray() As Integer = DirectCast(numbers.ToArray(GetType(Integer)), Integer ())
		Console.WriteLine("Converted Array:")
		For Each number As Integer In numbersArray
			Console.Write(number & " ")
		Next number
		Console.WriteLine(vbLf)
		' Demonstrate LINQ with ArrayList (Requires System.Linq)
		Dim evenNumbers = numbers.Cast(Of Integer)().Where(Function(n) n Mod 2 = 0).ToList() ' Assign values to evenNumbers from the filtered results.
		Console.WriteLine("Even Numbers:")
		evenNumbers.ForEach(Sub(n) Console.Write(n & " "))
		Console.WriteLine()
	End Sub
End Class
$vbLabelText   $csharpLabel

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

  • 使用一组元素初始化ArrayList
  • 将单个和多个元素添加到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.");
    }
}
Imports IronPdf
Imports System
Imports System.Collections
Friend Class pdfocde
	Shared Sub Main(ByVal args() As String)
		IronPdf.License.LicenseKey = "License"
		' Create a new ArrayList and add some items
		Dim itemList As New ArrayList()
		itemList.Add("Apple")
		itemList.Add("Banana")
		itemList.Add("Cherry")
		itemList.Add("Date")
		' Initialize a new PDF document
		Dim Renderer = New ChromePdfRenderer()
		' Create an HTML string to hold our content
		Dim htmlContent As String = "<h1>Items List</h1><ul>"
		' Iterate over each item in the ArrayList and add it to the HTML string
		For Each item In itemList
			htmlContent &= $"<li>{item}</li>"
		Next item
		htmlContent &= "</ul>"
		' Convert the HTML string to a PDF document
		Dim PDF = Renderer.RenderHtmlAsPdf(htmlContent)
		' Save the PDF to a file
		PDF.SaveAs("e:\ItemList.pdf")
		Console.WriteLine("PDF file 'ItemList.pdf' has been generated.")
	End Sub
End Class
$vbLabelText   $csharpLabel

在这个例子中,我们首先创建一个名为itemListArrayList,并用几个字符串项目填充它。 接下来,我们初始化一个新的 ChromePdfRenderer 类实例,它是 IronPDF 的一部分,我们将使用该实例将 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# 代码检查工具(开发人员如何使用)