C# ArrayList (개발자를 위한 작동 방식)
ArrayList 클래스는 .NET Framework의 컬렉션 네임스페이스의 부분이며, 객체의 컬렉션을 저장하도록 설계되었습니다. 이는 비제네릭 컬렉션으로, 모든 데이터 유형의 항목을 보유할 수 있다는 의미입니다. 이 기능은 높은 유연성을 제공하지만 제네릭 컬렉션에 비해 타입 안전성이 낮습니다. ArrayList는 중복 요소를 포함할 수 있으며, 유효한 값이 추가되거나 제거될 때 동적으로 크기를 조정할 수 있습니다. 이 기사에서는 ArrayList의 기본 사항과 IronPDF 라이브러리 기능에 대해 논의할 것입니다.
ArrayList의 기본 사항
ArrayList는 본질적으로 비제네릭 컬렉션으로, 모든 데이터 유형의 엘리먼트를 저장할 수 있어 다양한 프로그래밍 시나리오에서 유용한 선택입니다. 고정된 크기의 제약 없이 엘리먼트를 추가하거나 항목을 제거할 수 있는 능력은 그 주요 기능 중 하나입니다. ArrayList는 새로운 엘리먼트를 수용하기 위해 크기를 자동으로 조정하며, 이는 IList 인터페이스의 구현을 통해 가능해집니다. 이 동적 크기 조정은 수명 동안 엘리먼트 수가 다양할 수 있는 컬렉션이 필요한 응용 프로그램에 필수적입니다.
ArrayList를 인스턴스화할 때, 그것은 정수 및 문자열에서 복잡한 사용자 정의 객체에 이르기까지 모든 객체 값을 보유할 수 있는 컬렉션을 생성합니다. ArrayList에 엘리먼트를 추가하는 것은 Add와 같이 객체 값을 컬렉션의 끝에 붙이거나, Insert와 같이 새 항목을 지정된 인덱스에 배치하여 필요한 경우 기존 엘리먼트를 이동하는 메소드 덕분에 간단합니다. 이 유연성은 개발자가 응용 프로그램의 요구에 맞추어 컬렉션을 보다 효율적으로 관리할 수 있게 합니다.
요소 작업
ArrayList에 요소를 추가하는 것은 간단하고 직관적입니다. 예를 들어, 다양한 유형의 데이터를 수집하는 시나리오를 고려해 보세요. Add 메서드로 문자열부터 정수, 또는 다른 컬렉션까지 ArrayList에 모든 객체를 추가할 수 있습니다. ArrayList의 용량은 필요한 경우 자동으로 증가하여 항상 새로운 객체 요소를 위한 공간을 확보합니다. 이 자동 크기 조정은 추가적인 요소들을 수용하기 위해 수동으로 크기를 조절하거나 새 배열을 생성해야 하는 전통적인 배열보다 큰 장점입니다.
ArrayList는 특정 위치 또는 int 인덱스에서 요소를 삽입하고 제거하는 메서드도 제공합니다. Insert 메서드는 지정된 위치에 요소를 추가할 수 있어, 컬렉션 내에서 지정된 인덱스에 새 항목을 정확하게 배치할 수 있도록 합니다. 마찬가지로, Remove 및 RemoveAt 메서드는 삭제할 객체나 컬렉션 내 인덱스를 지정하여 항목을 삭제하는 데 도움을 줍니다. ArrayList 내 요소에 대한 세부적인 제어는 동적 데이터를 관리하는 강력한 도구가 됩니다.
요소 생성 및 추가
ArrayList 사용을 시작하려면 먼저 인스턴스를 생성해야 합니다. 그런 다음, Add 메서드를 사용하여 ArrayList의 끝에 객체를 삽입할 수 있습니다.
using System;
using System.Collections;
class Program
{
// The main entry point of the program
public static void Main()
{
// Create a new ArrayList
ArrayList myArrayList = new ArrayList();
// Add elements of different types
myArrayList.Add("Hello");
myArrayList.Add(100);
var item = "World";
myArrayList.Add(item);
// Iterate through the ArrayList and print each element
foreach (var obj in myArrayList)
{
Console.WriteLine(obj);
}
}
}
using System;
using System.Collections;
class Program
{
// The main entry point of the program
public static void Main()
{
// Create a new ArrayList
ArrayList myArrayList = new ArrayList();
// Add elements of different types
myArrayList.Add("Hello");
myArrayList.Add(100);
var item = "World";
myArrayList.Add(item);
// Iterate through the ArrayList and print each element
foreach (var obj in myArrayList)
{
Console.WriteLine(obj);
}
}
}
Imports System
Imports System.Collections
Friend Class Program
' The main entry point of the program
Public Shared Sub Main()
' Create a new ArrayList
Dim myArrayList As New ArrayList()
' Add elements of different types
myArrayList.Add("Hello")
myArrayList.Add(100)
Dim item = "World"
myArrayList.Add(item)
' Iterate through the ArrayList and print each element
For Each obj In myArrayList
Console.WriteLine(obj)
Next obj
End Sub
End Class

이 예는 새 ArrayList를 생성하고 다양한 유형의 요소를 추가하는 방법을 보여줍니다. 그런 다음 foreach 루프가 ArrayList를 순회하며 각 요소를 출력합니다.
요소 삽입
지정된 인덱스에 요소를 삽입하려면, 0부터 시작하는 인덱스 시스템임을 유의하며 Insert 메서드를 사용하십시오.
// Insert element at index 1
myArrayList.Insert(1, "Inserted Item");
// Insert element at index 1
myArrayList.Insert(1, "Inserted Item");
' Insert element at index 1
myArrayList.Insert(1, "Inserted Item")
요소 삭제
요소를 삭제하려면 Remove 및 RemoveAt 메서드를 활용하세요. 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
예제: 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
이 코드 스니펫은 다음을 수행하는 방법을 보여줍니다:
- 요소 집합으로 ArrayList를 초기화합니다.
- ArrayList에 단일 및 여러 요소를 추가합니다.
- 값으로, 인덱스로 요소를 삭제합니다.
- 요소를 정렬하여 ArrayList를 정렬합니다.
- 요소를 검색하고 그 인덱스를 찾습니다.
- ArrayList를 표준 배열로 변환합니다.
- LINQ를 사용하여 ArrayList에서 짝수를 필터링하고, 비제네릭 컬렉션과 LINQ의 강력한 쿼리 기능을 연결하는 방법을 보여줍니다.

IronPDF 소개: C# PDF 라이브러리

IronPDF는 복잡한 PDF 생성 과정을 단순화하는 강력한 C# 라이브러리로, HTML에서 PDF 생성, 텍스트 및 이미지 추가, 문서 보안 등 다양한 PDF 조작 기능을 제공합니다.
ArrayList와 IronPDF 통합하기
ArrayList의 항목을 생성한 뒤, IronPDF를 사용하여 그 항목들을 나열한 PDF 문서를 생성하는 간단한 C# 프로그램을 작성해 봅시다.
using IronPdf;
using System;
using System.Collections;
class PdfCode
{
static void Main(string[] args)
{
// Set your IronPDF license key here
IronPdf.License.LicenseKey = "Your_License_Key";
// 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("ItemList.pdf");
Console.WriteLine("PDF file 'ItemList.pdf' has been generated.");
}
}
using IronPdf;
using System;
using System.Collections;
class PdfCode
{
static void Main(string[] args)
{
// Set your IronPDF license key here
IronPdf.License.LicenseKey = "Your_License_Key";
// 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("ItemList.pdf");
Console.WriteLine("PDF file 'ItemList.pdf' has been generated.");
}
}
Imports IronPdf
Imports System
Imports System.Collections
Friend Class PdfCode
Shared Sub Main(ByVal args() As String)
' Set your IronPDF license key here
IronPdf.License.LicenseKey = "Your_License_Key"
' 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("ItemList.pdf")
Console.WriteLine("PDF file 'ItemList.pdf' has been generated.")
End Sub
End Class
이 예제에서 우리는 itemList라는 ArrayList를 생성하고 여러 문자열 항목으로 채웁니다. 다음으로, IronPDF의 ChromePdfRenderer 클래스를 초기화하여 HTML 콘텐츠를 PDF 문서로 변환할 겁니다.
출력
IronPDF로 생성한 출력 PDF는 다음과 같습니다:

결론

ArrayList는 객체 목록을 저장하기 위해 C#에서 제공하는 강력한 컬렉션입니다. 크기를 동적으로 조정하고 어떤 유형의 요소도 저장할 수 있어 다양한 애플리케이션에 유용합니다. 그러나 타입 안전성 및 더 나은 성능을 위해 제네릭 컬렉션을 추천합니다. ArrayList와 그 메서드를 실험하여 그 사용 용도와 애플리케이션에 어떻게 적합한지를 이해하세요.
또한, PDF 조작으로 C# 기능을 확장하고자 하는 사람들을 위해서 IronPDF는 .NET에서 PDF 기능을 탐색할 수 있는 무료 체험판을 제공합니다. 라이선스는 $799부터 시작하며, .NET 애플리케이션에 PDF 기능을 통합하기 위한 포괄적인 솔루션을 제공합니다.
자주 묻는 질문
ArrayList를 C#에서 PDF로 변환할 수 있는 방법은?
IronPDF를 사용하여 C#에서 ArrayList로부터의 PDF를 생성할 수 있습니다. ArrayList를 순회하면서 PDF 생성에 적합한 형식으로 내용을 컴파일한 후, IronPDF의 방법을 사용하여 PDF를 생성하고 저장하세요.
ArrayLists와 함께 IronPDF를 사용하면 얻을 수 있는 이점은 무엇인가요?
IronPDF를 사용하면 개발자는 ArrayLists에 저장된 데이터를 쉽게 PDF 문서로 변환할 수 있습니다. 이는 보고서를 작성하거나 최소한의 코드로 항목 목록을 내보내는 데 유용합니다.
ArrayList로 생성된 PDF에 텍스트와 이미지를 추가할 수 있나요?
네, IronPDF로 ArrayList의 항목을 순회하면서 텍스트, 이미지 및 다른 콘텐츠를 추가하여 PDF를 사용자 정의할 수 있습니다.
C#에서 ArrayList로 생성된 PDF를 보안할 수 있나요?
IronPDF는 PDF 문서를 보안할 수 있는 기능을 제공합니다. ArrayList의 데이터로 생성된 PDF의 접근 및 편집을 제한하는 암호 및 권한을 설정할 수 있습니다.
PDF 라이브러리와 통합할 때 ArrayList의 동적 크기 조정이 주는 이점은 무엇인가요?
ArrayList의 동적 크기 조정은 용량에 대해 걱정할 필요 없이 필요한 만큼 요소를 추가하거나 제거할 수 있도록 보장합니다. 이는 IronPDF와 같은 라이브러리를 사용하여 PDF 생성을 위해 데이터를 준비할 때 유용합니다.
C# 개발자에게 IronPDF를 사용한 이점은 무엇인가요?
IronPDF는 C# 개발자에게 PDF 문서를 생성하고 조작할 수 있는 강력한 도구 세트를 제공합니다. HTML을 PDF로 변환하기, 주석 추가, 여러 PDF 병합 등의 다양한 기능을 지원하여 .NET 애플리케이션에 필수적인 라이브러리로 자리매김하고 있습니다.
PDF를 생성할 때 ArrayList의 다양한 데이터 유형을 어떻게 처리할 수 있나요?
ArrayList는 어떤 데이터 유형도 저장할 수 있으므로 IronPDF를 사용하여 이 다양한 데이터 유형을 응집력 있는 PDF 문서로 변환 및 포맷할 수 있습니다. ArrayList를 순회하여 필요한 변환을 적용하세요.
ArrayLists와 함께 IronPDF를 사용하는 데 대한 문제 해결 팁은 무엇인가요?
ArrayList의 데이터가 PDF로 변환되기 전에 올바르게 형식화되었는지 확인하세요. null 값과 호환되지 않는 데이터 유형을 확인하고, PDF 생성 과정에서 발생하는 문제를 식별하고 해결하기 위해 IronPDF 디버깅 도구를 사용하세요.




