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

C# List (How it Works For Developers)

Lists are versatile and dynamic data structures used to store and manipulate collections of data in C#. They are part of the System.Collections.Generic namespace, which provides a range of powerful, type-safe collection classes and strongly typed objects. This beginner-friendly tutorial will guide you through the basics of using C# Lists, including how to create/add elements, access specified indices or first occurrences, modify specified elements, and remove elements, as well as some common use cases.

Creating Lists

To start using the List class, you first need to include the System.Collections.Generic namespace in your code:

using System.Collections.Generic;
using System.Collections.Generic;
$vbLabelText   $csharpLabel

After adding the generic namespace, create a new List object by specifying the data type of all the elements you want to store inside angular brackets (< >). Here's an example of how to create a list of integers:

List<int> numbers = new List<int>();
List<int> numbers = new List<int>();
$vbLabelText   $csharpLabel

You can also initialize a list with some initial values or define it by the specified collection like this:

List<string> fruits = new List<string> { "apple", "banana", "cherry" };
List<string> fruits = new List<string> { "apple", "banana", "cherry" };
$vbLabelText   $csharpLabel

We can also specify the default initial capacity of the list. The specified initial capacity is the default maximum capacity of the list.

Methods of List

Adding Number of Elements to a List

To add elements to your List, use the Add() method:

numbers.Add(1);     // Adds first element
numbers.Add(2);
numbers.Add(3);
numbers.Add(1);     // Adds first element
numbers.Add(2);
numbers.Add(3);
$vbLabelText   $csharpLabel

You can also add a range of elements from a specified collection to the list using the AddRange method:

List<int> moreNumbers = new List<int> { 4, 5, 6 };
numbers.AddRange(moreNumbers);
List<int> moreNumbers = new List<int> { 4, 5, 6 };
numbers.AddRange(moreNumbers);
$vbLabelText   $csharpLabel

Accessing List Elements

You can access individual elements of a list using an index, just like with arrays:

string firstFruit = fruits[0];          // "apple"
string secondFruit = fruits[1];         // "banana"
string firstFruit = fruits[0];          // "apple"
string secondFruit = fruits[1];         // "banana"
$vbLabelText   $csharpLabel

Keep in mind that lists are zero-based indexed, so the first element has an index of 0. The above example will store the element in the string if it exists.

Modifying List Elements

To modify an element in a list, simply assign a new value to the element at the desired index, keeping in mind the zero-based index:

fruits[1] = "blueberry";
fruits[1] = "blueberry";
$vbLabelText   $csharpLabel

Now, the second element in the fruits list is "blueberry" instead of "banana".

Removing Elements from a List

To remove an element from a list, you can use the Remove method, which removes the first occurrence of a specified element:

fruits.Remove("apple");
fruits.Remove("apple");
$vbLabelText   $csharpLabel

Alternatively, you can use the RemoveAt method to remove an element at the specified index:

fruits.RemoveAt(0);
fruits.RemoveAt(0);
$vbLabelText   $csharpLabel

To remove all elements from a list, use the Clear method:

fruits.Clear();
fruits.Clear();
$vbLabelText   $csharpLabel

Finding Elements in a List

You can use the Contains() method to check if a list contains a specific element:

bool containsApple = fruits.Contains("apple");  // true
bool containsApple = fruits.Contains("apple");  // true
$vbLabelText   $csharpLabel

To find the index of the first occurrence of an element, use the IndexOf method:

int appleIndex = fruits.IndexOf("apple");  // 0
int appleIndex = fruits.IndexOf("apple");  // 0
$vbLabelText   $csharpLabel

If the element is not found, IndexOf returns -1.

Looping Through a List

To iterate through the elements in a list, you can use a foreach loop:

foreach (string fruit in fruits)
{
    Console.WriteLine(fruit);
}
foreach (string fruit in fruits)
{
    Console.WriteLine(fruit);
}
$vbLabelText   $csharpLabel

Alternatively, you can use a for loop with the Count property, which returns the number of elements in the list:

for (int i = 0; i < fruits.Count; i++)
{
    Console.WriteLine(fruits[i]);
}
for (int i = 0; i < fruits.Count; i++)
{
    Console.WriteLine(fruits[i]);
}
$vbLabelText   $csharpLabel

Sorting a List

To sort a list in ascending order, use the Sort method:

List<int> unsortedNumbers = new List<int> { 5, 2, 8, 1, 4 };
unsortedNumbers.Sort();

// Now, unsortedNumbers is { 1, 2, 4, 5, 8 }
List<int> unsortedNumbers = new List<int> { 5, 2, 8, 1, 4 };
unsortedNumbers.Sort();

// Now, unsortedNumbers is { 1, 2, 4, 5, 8 }
$vbLabelText   $csharpLabel

To sort a list in descending order, you can use the Sort method with a custom comparison:

unsortedNumbers.Sort((a, b) => b.CompareTo(a));

// Now, unsortedNumbers is { 8, 5, 4, 2, 1 }
unsortedNumbers.Sort((a, b) => b.CompareTo(a));

// Now, unsortedNumbers is { 8, 5, 4, 2, 1 }
$vbLabelText   $csharpLabel

For more complex sorting, you can implement a custom IComparer class or use LINQ (Language Integrated Query). The binary search algorithm works on sorted lists.

Using LINQ with Lists

LINQ allows you to perform powerful queries and transformations on collections, including lists. To use LINQ, you first need to include the System.Linq namespace in your code:

using System.Linq;
using System.Linq;
$vbLabelText   $csharpLabel

Here are some examples of LINQ queries on a list:

Filtering a list

List<int> evenNumbers = numbers.Where(x => x % 2 == 0).ToList();
List<int> evenNumbers = numbers.Where(x => x % 2 == 0).ToList();
$vbLabelText   $csharpLabel

Mapping (transforming) Elements in a List

List<string> fruitNamesUpperCase = fruits.Select(x => x.ToUpper()).ToList();
List<string> fruitNamesUpperCase = fruits.Select(x => x.ToUpper()).ToList();
$vbLabelText   $csharpLabel

Finding the Minimum and Maximum Values in a List

int minValue = numbers.Min();
int maxValue = numbers.Max();
int minValue = numbers.Min();
int maxValue = numbers.Max();
$vbLabelText   $csharpLabel

Converting a List to an Array

To convert a list to an array, you can use the ToArray method:

int[] numbersArray = numbers.ToArray();
int[] numbersArray = numbers.ToArray();
$vbLabelText   $csharpLabel

Exporting List Data to a PDF Using IronPDF

In this section, we will demonstrate how to export the data in a List to a PDF file using the IronPDF library. This can be helpful when you want to generate a report or a printable version of your data.

First, download and install the IronPDF NuGet package to your project:

Install-Package IronPdf

Next, include the IronPdf namespace in your code:

using IronPdf;
using IronPdf;
$vbLabelText   $csharpLabel

Now, let's create a simple function that converts a List of strings into an HTML table and then exports it to a PDF file:

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

void ExportListToPdf(List<string> data, string pdfFilePath)
{
    // Create an HTML table from the list data
    StringBuilder htmlBuilder = new StringBuilder();
    htmlBuilder.Append("<table><tr><th>Item</th></tr>");

    foreach (string item in data)
    {
        htmlBuilder.Append($"<tr><td>{item}</td></tr>");
    }

    htmlBuilder.Append("</table>");

    // Convert the HTML table to a PDF using IronPDF
    var renderer = new ChromePdfRenderer();
    PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlBuilder.ToString());

    // Save the PDF to the specified file path
    pdf.SaveAs(pdfFilePath);
}
using System.Collections.Generic;
using System.Text;
using IronPdf;

void ExportListToPdf(List<string> data, string pdfFilePath)
{
    // Create an HTML table from the list data
    StringBuilder htmlBuilder = new StringBuilder();
    htmlBuilder.Append("<table><tr><th>Item</th></tr>");

    foreach (string item in data)
    {
        htmlBuilder.Append($"<tr><td>{item}</td></tr>");
    }

    htmlBuilder.Append("</table>");

    // Convert the HTML table to a PDF using IronPDF
    var renderer = new ChromePdfRenderer();
    PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlBuilder.ToString());

    // Save the PDF to the specified file path
    pdf.SaveAs(pdfFilePath);
}
$vbLabelText   $csharpLabel

To use this function, simply call it with your list and the desired PDF file path:

List<string> fruits = new List<string> { "apple", "banana", "cherry" };
ExportListToPdf(fruits, "Fruits.pdf");
List<string> fruits = new List<string> { "apple", "banana", "cherry" };
ExportListToPdf(fruits, "Fruits.pdf");
$vbLabelText   $csharpLabel

This will generate a PDF file named "Fruits.pdf" containing a table with the list of fruits by converting HTML to PDF with IronPDF. You can modify the ExportListToPdf function to suit your needs, such as adding custom styling to the HTML table or additional content to the PDF.

C# List (How It Works For Developers) Figure 1 - HTML to PDF

Conclusion

In this beginner-friendly tutorial, we covered the basics of using C# Lists and demonstrated how to integrate IronPDF to export List data to a PDF file. By incorporating IronPDF into your projects, you can easily generate reports, invoices, or other printable documents from your C# projects.

IronPDF offers a free trial, allowing you to test its capabilities before committing to a purchase.

자주 묻는 질문

C#으로 목록을 만들려면 어떻게 해야 하나요?

C#에서 리스트를 만들려면 System.Collections.Generic 네임스페이스를 포함해야 합니다. 그런 다음 꺾쇠 괄호 안에 데이터 유형을 지정하여 List를 선언할 수 있습니다. 예를 들어 List numbers = new List();

C# 목록에 요소를 추가하는 데는 어떤 방법이 사용되나요?

개별 요소의 경우 Add() 메서드를 사용하여 C# 목록에 요소를 추가하고 요소 모음을 추가할 때는 AddRange() 메서드를 사용하여 요소를 추가할 수 있습니다.

C# 목록을 PDF 파일로 내보내려면 어떻게 해야 하나요?

C# 리스트를 PDF 파일로 내보내려면 IronPDF 라이브러리를 사용하면 됩니다. 목록 데이터를 HTML 테이블 형식으로 변환한 다음 IronPDF를 사용하여 PDF로 렌더링합니다.

C# 목록을 정렬하는 가장 좋은 방법은 무엇인가요?

Sort() 메서드를 사용하여 C# 목록을 오름차순으로 정렬할 수 있습니다. 내림차순으로 정렬하려면 사용자 지정 비교 델리게이트와 함께 Sort()를 사용하면 됩니다.

C# 목록의 요소에 어떻게 액세스하나요?

C# 목록의 요소는 배열과 유사하게 인덱스를 사용하여 액세스할 수 있습니다. 목록은 0을 기준으로 인덱싱되므로 목록에서 요소의 위치를 사용하여 검색할 수 있습니다.

C# 목록에서 요소를 제거하려면 어떤 옵션을 사용할 수 있나요?

C# 목록에서 특정 요소의 경우 Remove() 메서드를 사용하여 요소를 제거하고, 특정 인덱스의 경우 RemoveAt(), 모든 요소를 제거하려면 Clear()를 사용하여 요소를 제거할 수 있습니다.

LINQ는 C# 목록과 함께 어떻게 활용할 수 있나요?

LINQ는 C# 목록과 함께 사용하여 필터링, 매핑, 최소값 또는 최대값 찾기와 같은 강력한 쿼리 및 변환을 효율적으로 수행할 수 있습니다.

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

목록의 요소를 포함하는 새 배열을 생성하는 ToArray() 메서드를 사용하여 C# 목록을 배열로 변환할 수 있습니다.

C# 목록의 일반적인 사용 사례에는 어떤 것이 있나요?

C# 목록은 일반적으로 동적 데이터 컬렉션을 관리하고, LINQ로 복잡한 쿼리를 수행하고, IronPDF와 같은 라이브러리를 사용하여 보고서나 문서를 생성하는 데 사용됩니다.

C# 목록의 요소를 어떻게 반복하나요?

간단한 반복을 위해 foreach 루프를 사용하거나 인덱스가 필요한 경우 for 루프를 사용하여 C# 목록의 요소를 반복할 수 있습니다.

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

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

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