푸터 콘텐츠로 바로가기
.NET 도움말

C# Initialize List (How It Works For Developers)

Lists are part of the System.Collections.Generic namespace and are versatile for handling collections of data. Lists in C# are dynamic, meaning their size can change at runtime. This flexibility is very helpful in many software engineering scenarios where the number of elements isn't known upfront. Let's dive into different ways to initialize a list in C#. We’ll cover basic techniques, object initializer syntax, collection initializers, and the IronPDF library.

Basic List Initialization

To initialize a list, start by creating an instance of the List<T> class, where T is the type of elements in the list. The most common type is string, but you can use any type.

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // Initialize an empty list
        List<string> fruits = new List<string>();

        // Adding elements to the list
        fruits.Add("Apple");
        fruits.Add("Banana");
        fruits.Add("Cherry");

        // Display the list
        foreach (var fruit in fruits)
        {
            Console.WriteLine(fruit);
        }
    }
}
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // Initialize an empty list
        List<string> fruits = new List<string>();

        // Adding elements to the list
        fruits.Add("Apple");
        fruits.Add("Banana");
        fruits.Add("Cherry");

        // Display the list
        foreach (var fruit in fruits)
        {
            Console.WriteLine(fruit);
        }
    }
}
$vbLabelText   $csharpLabel

In the example above, we created an empty list and added elements using the Add method. The List<string> represents a list of strings, and we used the Add method to populate it with values.

Using Collection Initializer Syntax

C# offers a more concise way to initialize a list using collection initializer syntax. This allows you to populate the list directly when it is created without repeatedly calling the Add method.

public void InitializeList()
{
    List<string> fruits = new List<string> { "Apple", "Banana", "Cherry" };
}
public void InitializeList()
{
    List<string> fruits = new List<string> { "Apple", "Banana", "Cherry" };
}
$vbLabelText   $csharpLabel

This code achieves the same result as the previous example but in a more compact form. Collection initializers allow you to initialize a list with values in a single statement, making your code more readable.

Object Initializers and List Initialization

Object initializer syntax is another way to initialize lists, mainly when working with custom objects. Here’s an example of how object initializers work with lists:

class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

List<Person> people = new List<Person>
{
    new Person { Name = "John", Age = 30 },
    new Person { Name = "Jane", Age = 25 },
    new Person { Name = "Jack", Age = 35 }
};
class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

List<Person> people = new List<Person>
{
    new Person { Name = "John", Age = 30 },
    new Person { Name = "Jane", Age = 25 },
    new Person { Name = "Jack", Age = 35 }
};
$vbLabelText   $csharpLabel

In this example, we create a list of Person objects using object initializers. The Person class has two properties: Name and Age, which are explicitly assigned values when the list is created.

Creating a List with an Initial Size

While lists are dynamic in size, you can specify an initial capacity if you know approximately how many elements the list will hold. This can improve performance by reducing the number of memory reallocations.

List<string> fruits = new List<string>(10); // Initial size of 10
List<string> fruits = new List<string>(10); // Initial size of 10
$vbLabelText   $csharpLabel

This creates an empty list with an initial capacity of 10. Although it doesn't add elements, it allocates enough memory to hold up to 10 elements without resizing the internal array.

Initializing a List from an Array

You can also initialize a list from an existing array using the list constructor that takes an IEnumerable<T> argument. This is useful when you have an array and want to convert it into a list for flexibility.

// New String array of fruit
string[] fruitArray = { "Apple", "Banana", "Cherry" };
List<string> fruits = new List<string>(fruitArray);
// New String array of fruit
string[] fruitArray = { "Apple", "Banana", "Cherry" };
List<string> fruits = new List<string>(fruitArray);
$vbLabelText   $csharpLabel

Here, a new array is created and then used to initialize a list. This converts the fruitArray array into a list. Any IEnumerable<T>, including arrays, can be passed to the list constructor for initialization.

Using the AddRange Method

If you have an existing collection of items, you can use the AddRange method to add multiple elements to a list together.

List<string> fruits = new List<string> { "Apple", "Banana" };
string[] moreFruits = { "Cherry", "Date", "Elderberry" };
fruits.AddRange(moreFruits);
List<string> fruits = new List<string> { "Apple", "Banana" };
string[] moreFruits = { "Cherry", "Date", "Elderberry" };
fruits.AddRange(moreFruits);
$vbLabelText   $csharpLabel

In this example, we start with a list containing two elements and add multiple new items from an array using AddRange. This method can improve performance by adding elements in bulk, as it minimizes the need for multiple reallocations.

Initializing a List with Custom Objects

When initializing a list of custom objects, you can combine object initializers with collection initializers to create complex data structures in a single expression.

List<Person> people = new List<Person>
{
    new Person { Name = "Alice", Age = 28 },
    new Person { Name = "Bob", Age = 32 },
    new Person { Name = "Charlie", Age = 40 }
};
List<Person> people = new List<Person>
{
    new Person { Name = "Alice", Age = 28 },
    new Person { Name = "Bob", Age = 32 },
    new Person { Name = "Charlie", Age = 40 }
};
$vbLabelText   $csharpLabel

This technique allows for creating and initializing a list of objects in a single statement, making the code concise and easy to read.

List Initialization with Extension Methods

You can also implement an extension method to initialize a list in a custom way. Extension methods provide a mechanism to improve existing types with new capabilities without altering their original structure.

public static class ListExtensions
{
    public static List<T> InitializeWith<T>(this List<T> list, params T[] elements)
    {
        list.AddRange(elements);
        return list;
    }
}

// Usage
List<string> fruits = new List<string>().InitializeWith("Apple", "Banana", "Cherry");
public static class ListExtensions
{
    public static List<T> InitializeWith<T>(this List<T> list, params T[] elements)
    {
        list.AddRange(elements);
        return list;
    }
}

// Usage
List<string> fruits = new List<string>().InitializeWith("Apple", "Banana", "Cherry");
$vbLabelText   $csharpLabel

Here, we define an extension method, InitializeWith, which adds elements to the list and returns the list itself. This allows you to chain the list's initialization and population.

IronPDF: C# PDF Library

C# Initialize List (How It Works For Developers): Figure 1 - IronPDF: The C# PDF Library

If you have a list, like a list of fruits, you can quickly turn it into an HTML table and render it as a PDF using IronPDF, all in just a few lines of code. The process is straightforward: initialize your list, convert it to HTML, and let IronPDF generate the PDF. Here’s an example:

using IronPdf;
using System;
using System.Collections.Generic;
using System.Text;

class Program
{
    static void Main()
    {
        // Initialize a list of strings representing data
        List<string> fruits = new List<string> { "Apple", "Banana", "Cherry" };

        // Convert the list to an HTML table
        StringBuilder htmlContent = new StringBuilder();
        htmlContent.Append("<table border='1'><tr><th>Fruit Name</th></tr>");
        foreach (var fruit in fruits)
        {
            htmlContent.Append($"<tr><td>{fruit}</td></tr>");
        }
        htmlContent.Append("</table>");

        // Render the HTML to PDF using IronPDF
        var Renderer = new ChromePdfRenderer();
        var PDF = Renderer.RenderHtmlAsPdf(htmlContent.ToString());

        // Save the PDF to a file
        PDF.SaveAs("FruitsList.pdf");
        Console.WriteLine("PDF generated successfully.");
    }
}
using IronPdf;
using System;
using System.Collections.Generic;
using System.Text;

class Program
{
    static void Main()
    {
        // Initialize a list of strings representing data
        List<string> fruits = new List<string> { "Apple", "Banana", "Cherry" };

        // Convert the list to an HTML table
        StringBuilder htmlContent = new StringBuilder();
        htmlContent.Append("<table border='1'><tr><th>Fruit Name</th></tr>");
        foreach (var fruit in fruits)
        {
            htmlContent.Append($"<tr><td>{fruit}</td></tr>");
        }
        htmlContent.Append("</table>");

        // Render the HTML to PDF using IronPDF
        var Renderer = new ChromePdfRenderer();
        var PDF = Renderer.RenderHtmlAsPdf(htmlContent.ToString());

        // Save the PDF to a file
        PDF.SaveAs("FruitsList.pdf");
        Console.WriteLine("PDF generated successfully.");
    }
}
$vbLabelText   $csharpLabel

C# Initialize List (How It Works For Developers): Figure 2 - Example output

This code initializes a list, creates an HTML table from it, and uses IronPDF to create a PDF file. It's a simple and direct way to generate PDFs from your data collections.

Conclusion

C# Initialize List (How It Works For Developers): Figure 3 - IronPDF licensing page

List initialization in C# is a fundamental concept that every software engineer should master. Whether you're working with simple lists of strings or complex lists of objects, C# offers several methods to initialize and populate lists efficiently. From basic initialization to object and collection initializers, these techniques help you write clean, concise, and maintainable code.

IronPDF offers a free trial that lets you try the product without making an initial investment. When you're confident it meets your needs, licenses are available starting at $799.

자주 묻는 질문

C#에서 목록을 초기화하는 기본 방법은 무엇인가요?

C#에서는 List 클래스의 인스턴스를 생성하여 목록을 초기화할 수 있으며, 여기서 T는 요소의 유형입니다. 예를 들어, List<string&t; fruits = new List<string&t;();는 목록을 초기화하는 기본적인 방법입니다.

컬렉션 이니셜라이저 구문은 C#에서 목록 초기화를 어떻게 개선할 수 있나요?

컬렉션 이니셜라이저 구문을 사용하면 목록을 만드는 동안 목록을 직접 채울 수 있으므로 코드를 더욱 간결하게 만들 수 있습니다. 예를 들어 List<string&t; fruits = new List<string&t; { 'Apple', 'Banana', 'Cherry' };.

목록을 초기화할 때 객체 초기화기 구문의 목적은 무엇인가요?

객체 초기화 구문은 사용자 지정 객체로 목록을 초기화할 때 유용하며, 목록을 만들 때 속성 값을 설정할 수 있습니다. 예를 들어 새로운 사람 { 이름 = 'John', 나이 = 30 }; 목록 내에서.

목록의 초기 용량을 설정할 수 있으며 그 이유는 무엇인가요?

예, 목록의 초기 용량을 설정하면 목록이 늘어날 때 메모리 재할당의 필요성을 줄여 성능을 향상시킬 수 있습니다. 예시 List<string&t; fruits = new List<string&t;(10);.

C#에서 기존 배열에서 목록을 초기화하려면 어떻게 해야 하나요?

리스트 생성자를 사용하여 배열에서 목록을 초기화할 수 있으며, 이 생성자는 IEnumerable<T<를 허용합니다. 예시 List<string&t; fruits = new List<string&t;(fruitArray);.

AddRange 메서드는 목록 초기화에서 어떤 역할을 하나요?

AddRange 메서드는 컬렉션의 여러 요소를 목록에 한 번에 추가하여 재할당을 최소화함으로써 성능을 최적화합니다. 예시 fruits.AddRange(moreFruits);.

이니셜라이저를 사용하여 목록에서 사용자 지정 개체를 초기화하려면 어떻게 해야 하나요?

객체 및 컬렉션 이니셜라이저의 조합을 사용하여 목록에서 사용자 지정 객체를 초기화할 수 있으므로 단일 표현식으로 목록을 만들 수 있습니다. 예시: new List<Person< { new Person { Name = 'Alice', Age = 28 } };.

확장 메서드란 무엇이며 목록 초기화와 어떤 관련이 있나요?

확장 메서드를 사용하면 기존 유형에 새로운 기능을 추가할 수 있습니다. 예를 들어, InitializeWith와 같은 확장 메서드를 작성하여 목록 초기화 및 채우기를 간소화할 수 있습니다.

C#에서 목록을 PDF로 변환하려면 어떻게 해야 하나요?

IronPDF를 사용하면 목록을 HTML 테이블로 변환하고 PDF로 렌더링하여 C#으로 데이터 컬렉션에서 PDF를 생성하는 프로세스를 간소화할 수 있습니다.

데이터 컬렉션에서 PDF를 생성하는 데 사용할 수 있는 무료 평가판이 있나요?

예, IronPDF는 무료 평가판을 제공하여 사용자가 초기 구매 없이 데이터 컬렉션에서 PDF 생성 기능을 테스트할 수 있습니다.

커티스 차우
기술 문서 작성자

커티스 차우는 칼턴 대학교에서 컴퓨터 과학 학사 학위를 취득했으며, Node.js, TypeScript, JavaScript, React를 전문으로 하는 프론트엔드 개발자입니다. 직관적이고 미적으로 뛰어난 사용자 인터페이스를 만드는 데 열정을 가진 그는 최신 프레임워크를 활용하고, 잘 구성되고 시각적으로 매력적인 매뉴얼을 제작하는 것을 즐깁니다.

커티스는 개발 분야 외에도 사물 인터넷(IoT)에 깊은 관심을 가지고 있으며, 하드웨어와 소프트웨어를 통합하는 혁신적인 방법을 연구합니다. 여가 시간에는 게임을 즐기거나 디스코드 봇을 만들면서 기술에 대한 애정과 창의성을 결합합니다.