C# Orderby (개발자를 위한 작동 방식)
정렬은 모든 프로그래밍 언어에서 기본적인 연산이며, C# OrderBy 메서드는 컬렉션 내 요소를 정렬하는 강력한 도구입니다. 배열, 목록 또는 기타 열거 가능한 구조와 작업할 때 OrderBy를 활용하는 방법을 이해하면 코드의 가독성과 기능성을 크게 향상시킬 수 있습니다.
이 후 이 기사에서는 Iron Software의 IronPDF 라이브러리와 LINQ OrderBy 메서드 및 IronPDF를 사용하여 정렬된 PDF를 생성하는 방법을 소개합니다.
LINQ OrderBy 메서드란?
OrderBy 메서드는 C#의 LINQ (Language-Integrated Query) 라이브러리에 속하여 요소를 오름차순으로 정렬하도록 특별히 설계되었습니다; 데이터를 정렬하는 기본적인 방법이므로 오름차순 키워드가 필요하지 않습니다.
LINQ OrderBy 메서드 사용 방법
오름차순 정렬
C#에서는 이 메서드를 적용할 수 있는 두 가지 방법이 있습니다: 메서드 구문 또는 쿼리 구문을 통해. 우리는 메서드 구문을 사용할 것입니다. 이는 간단합니다:
var sortedCollection = collection.OrderBy(item => item.OrderByProperty);
var sortedCollection = collection.OrderBy(item => item.OrderByProperty);
Dim sortedCollection = collection.OrderBy(Function(item) item.OrderByProperty)
여기에서 collection은(는) 정렬하고자 하는 IEnumerable 소스 컬렉션이며, OrderByProperty은(는) 요소를 정렬할 속성 또는 표현식입니다. OrderBy 내의 람다 표현식은 정렬 기준을 명시합니다.
내림차순 정렬
내림차순으로 정렬하기 위해서는 메서드 기반 문법을 사용하여 OrderByDescending 메서드를 사용할 수 있습니다:
var sortedCollectionDesc = collection.OrderByDescending(item => item.OrderByProperty);
var sortedCollectionDesc = collection.OrderByDescending(item => item.OrderByProperty);
Dim sortedCollectionDesc = collection.OrderByDescending(Function(item) item.OrderByProperty)
여러 기준으로 데이터 정렬
실제 시나리오에서는 컬렉션을 여러 기준에 따라 정렬해야 할 때가 많습니다. OrderBy은(는) 여러 ThenBy 또는 ThenByDescending 호출을 체이닝하여 이를 가능하게 합니다:
var multiSortedCollection = collection
.OrderBy(item => item.OrderByProperty1)
.ThenByDescending(item => item.OrderByProperty2);
var multiSortedCollection = collection
.OrderBy(item => item.OrderByProperty1)
.ThenByDescending(item => item.OrderByProperty2);
Dim multiSortedCollection = collection.OrderBy(Function(item) item.OrderByProperty1).ThenByDescending(Function(item) item.OrderByProperty2)
이 예시에서 컬렉션은 먼저 OrderByProperty1에 의해 오름차순으로 정렬됩니다. 그런 다음, 동일한 OrderByProperty1 값을 가진 요소들에 대해서는 OrderByProperty2에 의해 내림차순으로 정렬됩니다.
사용자 정의 비교자
더 복잡한 정렬 요구 사항을 위해 사용자 정의 비교자를 사용할 수 있습니다. OrderBy 메서드는 다음 예제에서와 같이 IComparer<t> 구현을 전달하도록 허용합니다:
var customSortedCollection = collection.OrderBy(item => item.Property, new CustomComparer());
var customSortedCollection = collection.OrderBy(item => item.Property, new CustomComparer());
Dim customSortedCollection = collection.OrderBy(Function(item) item.Property, New CustomComparer())
여기서 CustomComparer은(는) IComparer<t> 인터페이스를 구현하는 클래스이며, 요소를 비교하기 위한 사용자 지정 로직을 제공합니다.
실제 예: 객체 정렬
정수 목록 정렬
using System;
using System.Linq;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<int> numbers = new List<int> { 5, 2, 8, 1, 7 };
var sortedNumbers = numbers.OrderBy(num => num);
Console.WriteLine("Sorted Numbers:");
foreach (var number in sortedNumbers)
{
Console.WriteLine(number);
}
}
}
using System;
using System.Linq;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<int> numbers = new List<int> { 5, 2, 8, 1, 7 };
var sortedNumbers = numbers.OrderBy(num => num);
Console.WriteLine("Sorted Numbers:");
foreach (var number in sortedNumbers)
{
Console.WriteLine(number);
}
}
}
Imports System
Imports System.Linq
Imports System.Collections.Generic
Friend Class Program
Shared Sub Main()
Dim numbers As New List(Of Integer) From {5, 2, 8, 1, 7}
Dim sortedNumbers = numbers.OrderBy(Function(num) num)
Console.WriteLine("Sorted Numbers:")
For Each number In sortedNumbers
Console.WriteLine(number)
Next number
End Sub
End Class
이 예시에서 정수 리스트는 OrderBy을 사용하여 오름차순으로 정렬됩니다.
문자열 목록 정렬
using System;
using System.Linq;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<string> names = new List<string> { "Alice", "Charlie", "Bob", "David" };
var sortedNames = names.OrderBy(name => name);
Console.WriteLine("Sorted Names:");
foreach (var name in sortedNames)
{
Console.WriteLine(name);
}
}
}
using System;
using System.Linq;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<string> names = new List<string> { "Alice", "Charlie", "Bob", "David" };
var sortedNames = names.OrderBy(name => name);
Console.WriteLine("Sorted Names:");
foreach (var name in sortedNames)
{
Console.WriteLine(name);
}
}
}
Imports System
Imports System.Linq
Imports System.Collections.Generic
Friend Class Program
Shared Sub Main()
Dim names As New List(Of String) From {"Alice", "Charlie", "Bob", "David"}
Dim sortedNames = names.OrderBy(Function(name) name)
Console.WriteLine("Sorted Names:")
For Each name In sortedNames
Console.WriteLine(name)
Next name
End Sub
End Class
이 예는 문자열 목록을 알파벳 순서로 오름차순으로 정렬하는 방법을 보여줍니다.
사용자 정의 객체 목록 정렬
using System;
using System.Linq;
using System.Collections.Generic;
class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
}
class Program
{
static void Main()
{
List<Person> people = new List<Person>
{
new Person { FirstName = "John", LastName = "Doe", Age = 30 },
new Person { FirstName = "Alice", LastName = "Smith", Age = 25 },
new Person { FirstName = "Bob", LastName = "Johnson", Age = 35 }
};
var sortedPeople = people.OrderBy(person => person.Age);
Console.WriteLine("Sorted People by Age:");
foreach (var person in sortedPeople)
{
Console.WriteLine($"{person.FirstName} {person.LastName}, Age: {person.Age}");
}
}
}
using System;
using System.Linq;
using System.Collections.Generic;
class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
}
class Program
{
static void Main()
{
List<Person> people = new List<Person>
{
new Person { FirstName = "John", LastName = "Doe", Age = 30 },
new Person { FirstName = "Alice", LastName = "Smith", Age = 25 },
new Person { FirstName = "Bob", LastName = "Johnson", Age = 35 }
};
var sortedPeople = people.OrderBy(person => person.Age);
Console.WriteLine("Sorted People by Age:");
foreach (var person in sortedPeople)
{
Console.WriteLine($"{person.FirstName} {person.LastName}, Age: {person.Age}");
}
}
}
Imports System
Imports System.Linq
Imports System.Collections.Generic
Friend Class Person
Public Property FirstName() As String
Public Property LastName() As String
Public Property Age() As Integer
End Class
Friend Class Program
Shared Sub Main()
Dim people As New List(Of Person) From {
New Person With {
.FirstName = "John",
.LastName = "Doe",
.Age = 30
},
New Person With {
.FirstName = "Alice",
.LastName = "Smith",
.Age = 25
},
New Person With {
.FirstName = "Bob",
.LastName = "Johnson",
.Age = 35
}
}
Dim sortedPeople = people.OrderBy(Function(person) person.Age)
Console.WriteLine("Sorted People by Age:")
For Each person In sortedPeople
Console.WriteLine($"{person.FirstName} {person.LastName}, Age: {person.Age}")
Next person
End Sub
End Class
이 예시에서 사용자 지정 Person 객체의 리스트는 Age 속성을 기반으로 오름차순으로 정렬됩니다.
콘솔에서 출력 결과는 다음과 같습니다:

문자열 비교 처리
문자열 속성을 다룰 때 대소문자를 구분하지 않는 정렬을 보장하려고 할 수 있습니다:
var sortedPeopleByName = people.OrderBy(person => person.LastName, StringComparer.OrdinalIgnoreCase);
var sortedPeopleByName = people.OrderBy(person => person.LastName, StringComparer.OrdinalIgnoreCase);
Dim sortedPeopleByName = people.OrderBy(Function(person) person.LastName, StringComparer.OrdinalIgnoreCase)
이 예제는 StringComparer.OrdinalIgnoreCase을 사용하여 LastName 속성을 기반으로 대소문자를 구분하지 않고 정렬을 수행합니다.
성능 고려 사항
LINQ는 컬렉션을 정렬하는 데 간결한 방법을 제공하지만, 특히 대규모 데이터 세트의 경우 성능 영향을 고려하는 것이 중요합니다. 성능이 중요한 시나리오에서는 List<t>.Sort 메서드를 사용하여 제자리에서 정렬하는 것과 같은 대안을 탐색할 수 있습니다.
IronPDF 소개
IronPDF 기능 탐색을 통해 Iron Software의 C# PDF 라이브러리에서 PDF 문서를 읽고 생성하는 데 도움이 됩니다. 스타일 정보가 포함된 문서를 쉽게 PDF로 변환할 수 있습니다. IronPDF는 HTML 문자열로부터 PDF를 생성하거나, URL에서 HTML을 다운로드하여 PDF를 생성할 수 있습니다.
IronPDF는 HTML을 PDF로 변환하는 데 있어 모든 레이아웃과 스타일을 유지하며 우수한 성능을 발휘합니다. 보고서, 송장, 문서화 등의 다양한 웹 콘텐츠에서 PDF를 생성할 수 있습니다. 이 도구는 HTML 파일, URL, HTML 문자열을 사용하여 PDF 파일을 생성합니다.
using IronPdf;
class Program
{
static void Main(string[] args)
{
var renderer = new ChromePdfRenderer();
// 1. Convert HTML String to PDF
var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");
// 2. Convert HTML File to PDF
var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");
// 3. Convert URL to PDF
var url = "http://ironpdf.com"; // Specify the URL
var pdfFromUrl = renderer.RenderUrlAsPdf(url);
pdfFromUrl.SaveAs("URLToPDF.pdf");
}
}
using IronPdf;
class Program
{
static void Main(string[] args)
{
var renderer = new ChromePdfRenderer();
// 1. Convert HTML String to PDF
var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");
// 2. Convert HTML File to PDF
var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");
// 3. Convert URL to PDF
var url = "http://ironpdf.com"; // Specify the URL
var pdfFromUrl = renderer.RenderUrlAsPdf(url);
pdfFromUrl.SaveAs("URLToPDF.pdf");
}
}
Imports IronPdf
Friend Class Program
Shared Sub Main(ByVal args() As String)
Dim renderer = New ChromePdfRenderer()
' 1. Convert HTML String to PDF
Dim htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>"
Dim pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent)
pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf")
' 2. Convert HTML File to PDF
Dim htmlFilePath = "path_to_your_html_file.html" ' Specify the path to your HTML file
Dim pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath)
pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf")
' 3. Convert URL to PDF
Dim url = "http://ironpdf.com" ' Specify the URL
Dim pdfFromUrl = renderer.RenderUrlAsPdf(url)
pdfFromUrl.SaveAs("URLToPDF.pdf")
End Sub
End Class
설치
IronPDF는 NuGet 패키지 관리자 콘솔 또는 Visual Studio 패키지 관리자를 사용하여 설치할 수 있습니다.
Install-Package IronPdf
검색창에 "ironpdf"를 입력하여 NuGet 패키지 관리자를 사용하여 IronPDF를 설치할 수도 있습니다.

IronPDF를 사용한 PDF 생성
아래는 HTML 문자열과 IronPDF 생성기를 사용하여 PDF 보고서를 생성하는 코드입니다:
// See https://aka.ms/new-console-template for more information
using IronPdf;
using System;
using System.Collections.Generic;
using System.Linq;
class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
}
class Program
{
static void Main()
{
List<Person> people = new List<Person>
{
new Person { FirstName = "John", LastName = "Doe", Age = 30 },
new Person { FirstName = "Alice", LastName = "Smith", Age = 25 },
new Person { FirstName = "Bob", LastName = "Johnson", Age = 35 }
};
// Sort people by age
var sortedPeople = people.OrderBy(person => person.Age);
string name = "Sam";
var count = people.Count;
// Generate an HTML string
string content = $@"<!DOCTYPE html>
<html>
<body>
<h1>Hello, {name}!</h1>
<p>You have {count} people sorted by Age.</p>
" + string.Join("\n", sortedPeople.Select(person => $"{person.FirstName} {person.LastName}, Age: {person.Age}"))
+ @"
</body>
</html>";
// Create a new PDF document and save it
var pdfDocument = new ChromePdfRenderer();
pdfDocument.RenderHtmlAsPdf(content).SaveAs("personByAge.pdf");
}
}
// See https://aka.ms/new-console-template for more information
using IronPdf;
using System;
using System.Collections.Generic;
using System.Linq;
class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
}
class Program
{
static void Main()
{
List<Person> people = new List<Person>
{
new Person { FirstName = "John", LastName = "Doe", Age = 30 },
new Person { FirstName = "Alice", LastName = "Smith", Age = 25 },
new Person { FirstName = "Bob", LastName = "Johnson", Age = 35 }
};
// Sort people by age
var sortedPeople = people.OrderBy(person => person.Age);
string name = "Sam";
var count = people.Count;
// Generate an HTML string
string content = $@"<!DOCTYPE html>
<html>
<body>
<h1>Hello, {name}!</h1>
<p>You have {count} people sorted by Age.</p>
" + string.Join("\n", sortedPeople.Select(person => $"{person.FirstName} {person.LastName}, Age: {person.Age}"))
+ @"
</body>
</html>";
// Create a new PDF document and save it
var pdfDocument = new ChromePdfRenderer();
pdfDocument.RenderHtmlAsPdf(content).SaveAs("personByAge.pdf");
}
}
' See https://aka.ms/new-console-template for more information
Imports Microsoft.VisualBasic
Imports IronPdf
Imports System
Imports System.Collections.Generic
Imports System.Linq
Friend Class Person
Public Property FirstName() As String
Public Property LastName() As String
Public Property Age() As Integer
End Class
Friend Class Program
Shared Sub Main()
Dim people As New List(Of Person) From {
New Person With {
.FirstName = "John",
.LastName = "Doe",
.Age = 30
},
New Person With {
.FirstName = "Alice",
.LastName = "Smith",
.Age = 25
},
New Person With {
.FirstName = "Bob",
.LastName = "Johnson",
.Age = 35
}
}
' Sort people by age
Dim sortedPeople = people.OrderBy(Function(person) person.Age)
Dim name As String = "Sam"
Dim count = people.Count
' Generate an HTML string
Dim content As String = $"<!DOCTYPE html>
<html>
<body>
<h1>Hello, {name}!</h1>
<p>You have {count} people sorted by Age.</p>
" & String.Join(vbLf, sortedPeople.Select(Function(person) $"{person.FirstName} {person.LastName}, Age: {person.Age}")) & "
</body>
</html>"
' Create a new PDF document and save it
Dim pdfDocument = New ChromePdfRenderer()
pdfDocument.RenderHtmlAsPdf(content).SaveAs("personByAge.pdf")
End Sub
End Class
여기에서는 보고서에 필요한 모든 서식으로 오름차순으로 정렬된 sortedPeople에서 HTML 문자열을 처음 생성하고 있습니다. 그런 다음 IronPDF를 사용하여 PDF 문서를 생성합니다. 우리는 HTML 문자열을 PDF 문서로 변환하기 위해 RenderHtmlAsPdf 메서드를 사용합니다.
출력
PDF에서 다음 출력이 가능합니다:

라이센스 (무료 체험 가능)
IronPDF 체험판 라이선스에서 체험판 키를 얻을 수 있습니다. 이 키는 appsettings.json에 배치해야 합니다.
"IronPdf.LicenseKey": "your license key"
체험판 라이센스를 받으려면 이메일을 제공하세요.
결론
C#의 OrderBy 메서드는 다양한 기준에 따라 컬렉션을 정렬하는 데 유연한 도구입니다. 오름차순 또는 내림차순 정렬, 단일 또는 여러 기준에 따른 정렬, 사용자 정의 비교 선택 여부에 관계없이 OrderBy를 숙달하면 코드의 명확성과 효율성을 크게 향상시킬 수 있습니다.
PDF 문서를 생성하는 IronPDF 라이브러리와 함께, 문서를 아름답게 형식화하고 정렬된 컬렉션을 생성하는 데 훌륭한 조합입니다.
자주 묻는 질문
C# OrderBy 메서드는 어떻게 작동합니까?
LINQ 라이브러리의 일부인 C# OrderBy 메서드는 컬렉션의 요소를 오름차순으로 정렬합니다. 메서드 및 쿼리 구문 모두에서 사용할 수 있으며, 정수, 문자열 및 사용자 정의 객체를 처리할 수 있을 만큼 다재다능합니다.
C#에서 데이터를 내림차순으로 정렬할 수 있습니까?
C#에서 데이터를 내림차순으로 정렬하려면 OrderByDescending 메서드를 사용할 수 있습니다. 이는 LINQ 라이브러리의 일부이며, 다양한 정렬 요구를 위해 OrderBy를 보완합니다.
C#에서 여러 필드로 정렬하는 것이 가능합니까?
네, C#에서는 OrderBy에 ThenBy 또는 ThenByDescending을 조합하여 여러 필드로 정렬할 수 있습니다. 이는 여러 속성을 기반으로 컬렉션을 정렬할 수 있는 복잡한 정렬 기준을 허용합니다.
사용자 정의 비교자란 무엇이며 C# 정렬에서 어떻게 사용됩니까?
C#에서 사용자 지정 비교자는 IComparer 인터페이스의 구현으로, 정렬 중에 요소를 비교하기 위한 사용자 지정 로직을 제공합니다. 이는 복잡한 객체를 정렬하거나 기본 정렬 동작이 특정 요구 사항을 충족하지 못할 때 유용합니다.
IronPDF를 사용하여 C#에서 PDF를 생성하려면 어떻게 해야 합니까?
C#에서 IronPDF를 사용하여 HTML 문자열, 파일 또는 웹 URL에서 PDF를 생성할 수 있습니다. IronPDF는 원본 콘텐츠의 레이아웃과 스타일을 유지하므로 보고서나 송장과 같은 전문적인 문서를 작성하는 데 이상적입니다.
C# 프로젝트에 IronPDF를 설치하는 단계는 무엇입니까?
IronPDF는 NuGet 패키지 관리자를 통해 C# 프로젝트에 설치할 수 있습니다. 콘솔에서 dotnet add package IronPdf 명령을 실행하거나 Visual Studio의 패키지 관리자를 사용하여 프로젝트에 추가할 수 있습니다.
IronPDF와 C# OrderBy는 PDF 생성에 어떻게 통합됩니까?
IronPDF는 C# OrderBy와 통합되어 정렬되고 서식이 있는 PDF 보고서를 생성할 수 있습니다. 렌더링하기 전에 OrderBy를 사용하여 데이터 컬렉션을 정렬함으로써 PDF 출력이 정렬 기준에 따라 조직되도록 할 수 있습니다.
IronPDF가 웹 페이지 URL을 PDF로 변환할 수 있습니까?
네, IronPDF는 URL의 웹 콘텐츠를 PDF 문서로 변환할 수 있습니다. 이는 웹 페이지의 원래 레이아웃과 스타일을 보존하므로 웹 페이지를 보관하거나 인쇄 버전을 작성하는 데 적합합니다.




