.NET 帮助

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

发布 2024年三月6日
分享:

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

数组列表的基础知识

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

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

使用元素

ArrayList 中添加元素既简单又直观。例如,您可以建立一个包含各种类型数据的集合。使用Add方法,您可以向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
VB   C#

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

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

插入元素

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

myArrayList.Insert(1, "Inserted Item");
myArrayList.Insert(1, "Inserted Item");
myArrayList.Insert(1, "Inserted Item")
VB   C#

移除元素

要删除元素,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
VB   C#

示例管理数组列表

在 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
VB   C#

本代码片段演示了如何操作:

  • 用一组元素初始化数组列表
  • ArrayList 添加单个或多个元素。
  • 按值和索引删除元素
  • 数组列表排序,对元素进行排序。
  • 搜索元素并查找其索引。
  • ArrayList 转换为标准数组。

  • 使用 LINQ 与 ArrayList,过滤出偶数,展示如何利用 LINQ 强大的查询功能连接非通用集合。

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

IronPDF 简介:C# PDF Library

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

IronPDF 是一个功能强大的 C# 库,它简化了复杂的 PDF 生成过程,为 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
VB   C#

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

输出

下面是 IronPDF 生成的 PDF 输出结果:

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

结论

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

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

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

< 前一页
Math.Round C# (它是如何为开发人员工作的)
下一步 >
C# 代码检查工具(开发人员如何使用)

准备开始了吗? 版本: 2024.9 刚刚发布

免费NuGet下载 总下载量: 10,731,156 查看许可证 >