
C# LINQ Distinct (개발자를 위한 작동 원리)
언어 통합 쿼리(LINQ)는 C#의 강력한 언어 기능으로, 프로그래머가 다양한 데이터 소스를 위해 명확하고 표현적인 쿼리를 생성할 수 있게 해줍니다. 이 게시물에서는 PDF 문서를 처리하기 위한 다재다능한 C# 라이브러리인 IronPDF를 사용하여 LINQ의 Distinct 함수를 활용하는 방법을 논의할 것입니다. 이러한 조합이 컬렉션에서 고유한 문서를 만드는 프로세스를 어떻게 더 쉽게 할 수 있는지 보여드리겠습니다. 이 기사에서는 IronPDF와 함께 C# LINQ의 Distinct 기능에 대해 배워보겠습니다.
C# LINQ Distinct 메서드 사용 방법
- 새로운 콘솔 프로젝트를 생성합니다.
System.Linq네임스페이스를 가져옵니다.- 여러 항목이 포함된 리스트를 만듭니다.
- List에서
Distinct()메소드를 호출합니다. - 고유한 값을 얻고 콘솔에 결과를 표시합니다.
- 생성된 모든 객체를 폐기합니다.
LINQ란 무엇인가
개발자는 C#의 LINQ (Language Integrated Query) 기능을 통해 데이터 조작을 위한 명확하고 표현적인 쿼리를 직접 코드에 작성할 수 있습니다. .NET Framework 3.5에 처음 포함된 LINQ는 데이터베이스 및 컬렉션을 비롯한 다양한 데이터 소스를 쿼리하는 표준 문법을 제공합니다. LINQ는 Where 및 Select와 같은 연산자를 사용하여 필터링 및 프로젝션과 같은 간단한 작업을 쉽게 하여 코드 가독성을 향상시킵니다. 최적의 속도를 위한 지연 실행을 허용하기 때문에, 이 기능은 C# 개발자에게 데이터 조작 작업이 SQL과 유사한 방식으로 신속하고 자연스럽게 완료되도록 하는 데 매우 중요합니다.
LINQ Distinct 이해하기
중복 요소는 LINQ의 Distinct 함수를 사용하여 컬렉션 또는 시퀀스에서 제거할 수 있습니다. 사용자 정의 비교기가 없으면, 기본 비교기를 사용하여 항목을 비교합니다. 이런 상황에서 고유한 컬렉션으로 작업하고 중복 요소를 제거해야 할 때 훌륭한 선택이 됩니다. Distinct 기법은 기본 동등 비교자를 사용하여 값을 평가합니다. 중복을 배제하여 고유한 요소만 반환합니다.
기본 사용법
고유한 항목을 얻기 위해 이를 사용하는 가장 간단한 방법은 Distinct 메소드를 컬렉션에 직접 사용하는 것입니다.
using System.Linq;
using System.Collections.Generic;
public class DistinctExample
{
public static void Example()
{
// Example list with duplicate integers
List<int> numbers = new List<int> { 1, 2, 2, 3, 4, 4, 5 };
// Using Distinct to remove duplicates
var distinctNumbers = numbers.Distinct();
// Display the distinct numbers
foreach (var number in distinctNumbers)
{
Console.WriteLine(number);
}
}
}Imports System.Linq
Imports System.Collections.Generic
Public Class DistinctExample
Public Shared Sub Example()
' Example list with duplicate integers
Dim numbers As New List(Of Integer) From {1, 2, 2, 3, 4, 4, 5}
' Using Distinct to remove duplicates
Dim distinctNumbers = numbers.Distinct()
' Display the distinct numbers
For Each number In distinctNumbers
Console.WriteLine(number)
Next number
End Sub
End Class사용자 정의 동등 비교자
Distinct 함수의 오버로드를 사용하여 사용자 정의 동등 비교를 정의할 수 있습니다. 특정 기준에 따라 항목을 비교하고 싶을 때 유용합니다. 다음 예제를 참조하십시오:
using System;
using System.Collections.Generic;
using System.Linq;
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class PersonEqualityComparer : IEqualityComparer<Person>
{
public bool Equals(Person x, Person y)
{
return x.FirstName == y.FirstName && x.LastName == y.LastName;
}
public int GetHashCode(Person obj)
{
return obj.FirstName.GetHashCode() ^ obj.LastName.GetHashCode();
}
}
public class DistinctCustomComparerExample
{
public static void Example()
{
// Example list of people
List<Person> people = new List<Person>
{
new Person { FirstName = "John", LastName = "Doe" },
new Person { FirstName = "Jane", LastName = "Doe" },
new Person { FirstName = "John", LastName = "Doe" }
};
// Using Distinct with a custom equality comparer
var distinctPeople = people.Distinct(new PersonEqualityComparer());
// Display distinct people
foreach (var person in distinctPeople)
{
Console.WriteLine($"{person.FirstName} {person.LastName}");
}
}
}Imports System
Imports System.Collections.Generic
Imports System.Linq
Public Class Person
Public Property FirstName() As String
Public Property LastName() As String
End Class
Public Class PersonEqualityComparer
Implements IEqualityComparer(Of Person)
Public Function Equals(ByVal x As Person, ByVal y As Person) As Boolean Implements IEqualityComparer(Of Person).Equals
Return x.FirstName = y.FirstName AndAlso x.LastName = y.LastName
End Function
Public Function GetHashCode(ByVal obj As Person) As Integer Implements IEqualityComparer(Of Person).GetHashCode
Return obj.FirstName.GetHashCode() Xor obj.LastName.GetHashCode()
End Function
End Class
Public Class DistinctCustomComparerExample
Public Shared Sub Example()
' Example list of people
Dim people As New List(Of Person) From {
New Person With {
.FirstName = "John",
.LastName = "Doe"
},
New Person With {
.FirstName = "Jane",
.LastName = "Doe"
},
New Person With {
.FirstName = "John",
.LastName = "Doe"
}
}
' Using Distinct with a custom equality comparer
Dim distinctPeople = people.Distinct(New PersonEqualityComparer())
' Display distinct people
For Each person In distinctPeople
Console.WriteLine($"{person.FirstName} {person.LastName}")
Next person
End Sub
End Class값 형식과 Distinct 사용하기
Distinct 메소드를 값 유형과 함께 사용할 때는 사용자 정의 동등 비교를 제공할 필요가 없습니다.
using System;
using System.Collections.Generic;
using System.Linq;
public class DistinctValueTypeExample
{
public static void Example()
{
List<int> integers = new List<int> { 1, 2, 2, 3, 4, 4, 5 };
// Using Distinct to remove duplicates
var distinctIntegers = integers.Distinct();
// Display distinct integers
foreach (var integer in distinctIntegers)
{
Console.WriteLine(integer);
}
}
}Imports System
Imports System.Collections.Generic
Imports System.Linq
Public Class DistinctValueTypeExample
Public Shared Sub Example()
Dim integers As New List(Of Integer) From {1, 2, 2, 3, 4, 4, 5}
' Using Distinct to remove duplicates
Dim distinctIntegers = integers.Distinct()
' Display distinct integers
For Each [integer] In distinctIntegers
Console.WriteLine([integer])
Next [integer]
End Sub
End Class익명 형식과 Distinct 사용하기
Distinct를 익명 타입과 함께 사용하여 특정 속성을 기반으로 중복을 제거할 수 있습니다. 다음 예제를 참조하십시오:
using System;
using System.Collections.Generic;
using System.Linq;
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class DistinctAnonymousTypesExample
{
public static void Example()
{
List<Person> people = new List<Person>
{
new Person { FirstName = "John", LastName = "Doe" },
new Person { FirstName = "Jane", LastName = "Doe" },
new Person { FirstName = "John", LastName = "Doe" }
};
// Using Distinct with anonymous types
var distinctPeople = people
.Select(p => new { p.FirstName, p.LastName })
.Distinct();
// Display distinct anonymous types
foreach (var person in distinctPeople)
{
Console.WriteLine($"{person.FirstName} {person.LastName}");
}
}
}Imports System
Imports System.Collections.Generic
Imports System.Linq
Public Class Person
Public Property FirstName() As String
Public Property LastName() As String
End Class
Public Class DistinctAnonymousTypesExample
Public Shared Sub Example()
Dim people As New List(Of Person) From {
New Person With {
.FirstName = "John",
.LastName = "Doe"
},
New Person With {
.FirstName = "Jane",
.LastName = "Doe"
},
New Person With {
.FirstName = "John",
.LastName = "Doe"
}
}
' Using Distinct with anonymous types
Dim distinctPeople = people.Select(Function(p) New With {
Key p.FirstName,
Key p.LastName
}).Distinct()
' Display distinct anonymous types
For Each person In distinctPeople
Console.WriteLine($"{person.FirstName} {person.LastName}")
Next person
End Sub
End Class특정 속성에 따라 Distinct 하기
객체를 다룰 때는 특정 속성을 구분하기 위한 로직을 생성하거나, 타사 라이브러리(예: MoreLINQ)에서 제공하는 DistinctBy 확장 메소드를 사용할 수 있습니다.
// Ensure to include the MoreLINQ Library
using MoreLinq;
using System;
using System.Collections.Generic;
using System.Linq;
public class Person
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class DistinctByExample
{
public static void Example()
{
List<Person> people = new List<Person>
{
new Person { Id = 1, FirstName = "John", LastName = "Doe" },
new Person { Id = 2, FirstName = "Jane", LastName = "Doe" },
new Person { Id = 1, FirstName = "John", LastName = "Doe" }
};
// Using DistinctBy to filter distinct people by Id
var distinctPeople = people.DistinctBy(p => p.Id);
// Display distinct people
foreach (var person in distinctPeople)
{
Console.WriteLine($"{person.Id}: {person.FirstName} {person.LastName}");
}
}
}' Ensure to include the MoreLINQ Library
Imports MoreLinq
Imports System
Imports System.Collections.Generic
Imports System.Linq
Public Class Person
Public Property Id() As Integer
Public Property FirstName() As String
Public Property LastName() As String
End Class
Public Class DistinctByExample
Public Shared Sub Example()
Dim people As New List(Of Person) From {
New Person With {
.Id = 1,
.FirstName = "John",
.LastName = "Doe"
},
New Person With {
.Id = 2,
.FirstName = "Jane",
.LastName = "Doe"
},
New Person With {
.Id = 1,
.FirstName = "John",
.LastName = "Doe"
}
}
' Using DistinctBy to filter distinct people by Id
Dim distinctPeople = people.DistinctBy(Function(p) p.Id)
' Display distinct people
For Each person In distinctPeople
Console.WriteLine($"{person.Id}: {person.FirstName} {person.LastName}")
Next person
End Sub
End ClassIronPDF
프로그래머는 .NET 라이브러리인 IronPDF Website의 도움으로 C# 언어를 사용하여 PDF 문서를 생성, 편집 및 수정할 수 있습니다. 프로그램은 HTML에서 PDF 파일 생성, HTML을 PDF로 변환, PDF 문서 병합 또는 분할, 기존 PDF에 텍스트, 이미지 및 주석 추가 등 PDF 파일 관련 다양한 작업을 지원하는 도구와 기능을 제공합니다. IronPDF에 대해 더 알고 싶으시면 IronPDF Documentation을 참조하세요.
IronPDF의 주요 기능은 HTML to PDF Conversion으로, 레이아웃과 스타일을 그대로 유지합니다. 웹 콘텐츠에서 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");
}
}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 ClassIronPDF 의 특징
- HTML을 PDF로 변환: IronPDF를 사용하면 파일, URL 및 HTML 코드 문자열을 포함한 모든 종류의 HTML 데이터를 PDF 문서로 변환할 수 있습니다.
- PDF 생성: C# 프로그래밍 언어를 사용하여 텍스트, 이미지 및 기타 요소를 PDF 문서에 프로그래밍 방식으로 추가할 수 있습니다.
- PDF 조작: IronPDF는 PDF 파일을 여러 파일로 분할하거나 여러 PDF 문서를 하나의 파일로 병합하고 기존 PDF를 편집할 수 있습니다.
- PDF 양식: 라이브러리는 사용자들이 PDF 양식을 작성하고 작성할 수 있도록 하여, 양식 데이터를 수집하고 처리해야 하는 경우에 유용합니다.
- 보안 기능: IronPDF는 PDF 문서를 암호화하고 비밀번호 및 권한 보호를 제공하기 위해 사용될 수 있습니다.
- 텍스트 추출: IronPDF를 사용하여 PDF 파일에서 텍스트를 추출할 수 있습니다.
IronPDF를 설치하세요
IronPDF 라이브러리를 얻으십시오; 프로젝트 설정을 위해 필요합니다. 이를 실행하려면 NuGet 패키지 관리자 콘솔에 다음 코드를 입력하세요:

NuGet 패키지 관리자에서 "IronPDF" 패키지를 검색하는 것이 또 다른 선택입니다. IronPDF와 관련된 모든 NuGet 패키지 목록에서 필요한 패키지를 선택하고 다운로드할 수 있습니다.

IronPDF와 함께하는 LINQ
여러분이 데이터 세트를 가지고 있고 해당 세트의 다른 값에 따라 다양한 PDF 문서를 생성하고 싶어하는 상황을 고려해 보세요. 이는 특히 IronPDF와 결합하여 문서를 빠르게 생성할 때 LINQ의 Distinct 유용성이 빛을 발하는 부분입니다.
LINQ와 IronPDF로 고유한 PDF 생성
using IronPdf;
using System;
using System.Collections.Generic;
using System.Linq;
public class DocumentGenerator
{
public static void Main()
{
// Sample data representing categories
List<string> categories = new List<string>
{
"Technology",
"Business",
"Health",
"Technology",
"Science",
"Business",
"Health"
};
// Use LINQ Distinct to filter out duplicate values
var distinctCategories = categories.Distinct();
// Generate a distinct elements PDF document for each category
foreach (var category in distinctCategories)
{
GeneratePdfDocument(category);
}
}
private static void GeneratePdfDocument(string category)
{
// Create a new PDF document using IronPDF
IronPdf.HtmlToPdf renderer = new IronPdf.HtmlToPdf();
PdfDocument pdf = renderer.RenderHtmlAsPdf($"<h1>{category} Report</h1>");
// Save the PDF to a file
string pdfFilePath = $"{category}_Report.pdf";
pdf.SaveAs(pdfFilePath);
// Display a message with the file path
Console.WriteLine($"PDF generated successfully. File saved at: {pdfFilePath}");
}
}Imports IronPdf
Imports System
Imports System.Collections.Generic
Imports System.Linq
Public Class DocumentGenerator
Public Shared Sub Main()
' Sample data representing categories
Dim categories As New List(Of String) From {
"Technology",
"Business",
"Health",
"Technology",
"Science",
"Business",
"Health"
}
' Use LINQ Distinct to filter out duplicate values
Dim distinctCategories = categories.Distinct()
' Generate a distinct elements PDF document for each category
For Each category In distinctCategories
GeneratePdfDocument(category)
Next
End Sub
Private Shared Sub GeneratePdfDocument(ByVal category As String)
' Create a new PDF document using IronPDF
Dim renderer As New IronPdf.HtmlToPdf()
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf($"<h1>{category} Report</h1>")
' Save the PDF to a file
Dim pdfFilePath As String = $"{category}_Report.pdf"
pdf.SaveAs(pdfFilePath)
' Display a message with the file path
Console.WriteLine($"PDF generated successfully. File saved at: {pdfFilePath}")
End Sub
End Class이 예제에서는 카테고리 컬렉션에 대해 Distinct 메소드를 사용하여 일련의 고유한 카테고리를 얻습니다. 시퀀스에서 중복 요소를 제거하는 데 도움이 됩니다. 다음으로, IronPDF는 이러한 고유 요소로 PDF 문서를 생성하는 데 사용됩니다. 이 방법은 고유한 카테고리별로 별도의 PDF 문서를 생성하는 것을 보장합니다.
콘솔 출력

생성된 PDF 출력

HTML을 사용하여 PDF를 생성하는 IronPDF 코드 예제를 더 알고 싶다면 IronPDF HTML로 PDF 예제 코드를 참조하세요.
결론
LINQ의 Distinct 확장 메소드는 IronPDF와 결합하여 값에 기반한 고유한 PDF 문서를 생성할 수 있는 강력하고 효율적인 메커니즘을 제공합니다. 이 방법은 카테고리, 태그, 또는 별도의 문서가 필요한 다른 데이터와 작업하든 코드의 단순화와 효과적인 문서 생성 보장을 가져옵니다.
LINQ를 이용한 데이터 처리와 IronPDF를 이용한 문서 생성을 통해 C# 애플리케이션의 다양한 측면을 관리하기 위한 신뢰성 있고 표현력 있는 솔루션을 개발할 수 있습니다. 프로젝트에 이러한 전략을 사용할 때 애플리케이션의 특정 요구 사항을 염두에 두고 최대 신뢰성과 성능을 달성하기 위해 구현을 조정하세요.

제이콥 멜러는 Iron Software의 최고 기술 책임자(CTO)이자 C# PDF 기술을 개척한 선구적인 엔지니어입니다. Iron Software의 핵심 코드베이스를 최초로 개발한 그는 창립 초기부터 회사의 제품 아키텍처를 설계해 왔으며, CEO인 캐머런 리밍턴과 함께 회사를 NASA, 테슬라, 그리고 전 세계 정부 기관에 서비스를 제공하는 50명 이상의 직원을 보유한 기업으로 성장시켰습니다.
관련 기사


