C# LINQ Distinct (對開發者如何運作)
語言整合查詢 (LINQ),是 C# 中一個強大的語言功能,可讓程式設計師針對各種資料來源建立清晰、具表現力的查詢。 本篇文章將討論 IronPDF(一個用於處理 PDF 文件的多功能 C# 函式庫)使用 LINQ 的 Distinct 函式。 我們將說明這種組合可能如何讓從集合中建立獨特文件的過程變得更容易。 在這篇文章中,我們將學習 C# LINQ distinct 函數與 IronPDF。
如何使用 C# LINQ Distinct 方法
1.建立一個新的主控台專案。
- 導入
System.Linq命名空間。 3.建立包含多項目的清單。 - 從清單中呼叫方法
Distinct()。 5.取得唯一值並在控制台顯示結果。 6.處理所有建立的物件。
什麼是 LINQ
開發人員可利用 C# 的 LINQ(語言整合查詢)功能,直接在程式碼中建立清晰且具表達力的查詢,以進行資料處理。 LINQ 首次包含在 .NET Framework 3.5 中,提供了查詢一系列資料來源(包括資料庫和集合)的標準語法。 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);
}
}
}
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}");
}
}
}
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 方法處理值類型時,不需要提供自訂相等性比較。
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);
}
}
}
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 可以與匿名類型一起使用,根據特定屬性刪除重複項。 請參考以下範例:
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}");
}
}
}
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
以特定屬性區分
在處理物件時,您可以建立自己的邏輯來透過某個屬性進行區分,或者您可以使用來自第三方程式庫(如 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
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 Class
IronPDF
程式設計師可借助 .NET 函式庫 IronPDF 網站,使用 C# 語言建立、編輯和修改 PDF 文件。 該程式提供了一系列工具和功能,以實現涉及 PDF 檔案的各種任務,例如從 HTML 生成 PDF、將 HTML 轉換為 PDF、合併或分割 PDF 文件,以及在已存在的 PDF 中添加文字、圖像和註釋。 若要瞭解 IronPDF 的更多資訊,請參閱其 IronPDF 文件。
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 的功能
- 將 HTML 轉換為 PDF: 您可以使用 IronPDF 將任何類型的 HTML 資料 - 包括檔案、URL 和 HTML 程式碼串 - 轉換為 PDF 文件。
- PDF 生成:可使用 C# 程式設計語言以程式設計方式將文字、圖像和其他元素新增到 PDF 文件中。
- PDF操縱: IronPDF 可以將一個 PDF 檔案分割成許多檔案、將多個 PDF 文件合併成一個檔案,以及編輯已經存在的 PDF 檔案。
- PDF 表單:該函式庫可讓使用者建立和填寫 PDF 表單,因此在需要收集和處理表單資料的場合中非常有用。
- 安全功能: IronPDF 可用於加密 PDF 文件,並提供密碼和權限保護。
- 文字萃取:可使用 IronPDF 從 PDF 檔案中萃取文字。
安裝 IronPDF
取得 IronPDF 函式庫; 這是建立專案所需要的。 在 NuGet Package Manager Console 中輸入以下程式碼即可完成:
Install-Package IronPdf
。
使用 NuGet Package Manager 搜尋套件"IronPDF"是另一個選擇。我們可以從與 IronPDF 相關的所有 NuGet 套件中,選擇並下載此清單中所需的套件。

LINQ 與 IronPDF
考慮一種情況:您有一組資料,您希望根據這組資料中的不同值建立各種 PDF 文件。 LINQ 的 Distinct 的實用性在這裡就體現出來了,尤其是在與 IronPDF 一起使用以快速建立文件時。
使用 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}");
}
}
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 category
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 輸出

若要瞭解更多關於 IronPDF 使用 HTML 產生 PDF 的程式碼範例,請參閱 IronPDF HTML to PDF 範例程式碼。
結論
LINQ 的 Distinct 擴充方法與 IronPDF 結合使用,提供了一個強大而高效的機制,可以根據值建立獨特的 PDF 文件。 無論您是處理分類、標籤或任何其他需要獨立文件的資料,此方法都能簡化程式碼並保證有效的文件製作。
您可以利用 LINQ 進行資料處理,並利用 IronPDF 製作文件,開發出可靠且具表現力的解詴,以管理 C# 應用程式的不同方面。 在您的專案中使用這些策略時,請牢記您應用程式的特殊需求,並調整實作,以達到最高的可靠性和效能。
常見問題解答
如何移除 C# 集合中的重複條目?
您可以使用 LINQ 的 Distinct 方法來移除 C# 集合中的重複條目。此方法在與 IronPDF 結合使用時特別有用,可用於從不同資料類別生成唯一的 PDF 文件。
如何在 C# 中將 HTML 轉換為 PDF?
要在 C# 中將 HTML 轉換為 PDF,您可以使用 IronPDF 的 RenderHtmlAsPdf 方法。這使您可以高效地將 HTML 字串或文件轉換為 PDF 文件。
我可以在自訂物件上使用 LINQ 的 Distinct 方法嗎?
是的,您可以透過提供自訂等值比較器來在自訂物件上使用 LINQ 的 Distinct 方法。這在您需要針對 PDF 生成過程中的唯一性定義特定標準時非常有用。
使用 LINQ 與 IronPDF 的好處是什麼?
使用 LINQ 與 IronPDF 能讓開發者基於資料處理建立獨特且高效的 PDF 文件。當處理大規模文件生成任務時,它增強了程式碼的可讀性和性能。
LINQ 的 Distinct 方法如何增強 PDF 文件建立?
LINQ 的 Distinct 方法能夠確保最終輸出中僅包含唯一的條目,從而增強 PDF 文件的建立。此方法可以與 IronPDF 結合,用於為各種資料類別生成不同的 PDF 文件。
使用 IronPDF 時,是否可以定制 PDF 的輸出?
可以,IronPDF 提供了多種選項來定制 PDF 輸出,包括設置頁面大小、邊距以及添加頁首或頁尾。這些定制可以與 LINQ 結合,建立量身定制的唯一文件輸出。
哪些情況可以從使用與 PDFs 相關的 LINQ 的 Distinct 方法中受益?
生成報告、發票或任何需要確保資料集唯一性的文件等情況可以從使用與 PDFs 相關的 LINQ 的 Distinct 方法中受益。IronPDF 可以有效地生成清晰且獨特的 PDF 輸出。
LINQ 如何提高資料驅動 PDF 應用程式的效率?
LINQ 透過允許開發者在生成 PDF 之前篩選和操作資料集,從而提高資料驅動 PDF 應用程式的效率。這確保 PDF 中僅包含必要且唯一的資料,從而優化性能和資源使用。



