C# LINQ Distinct (對開發者如何運作)
語言整合查詢 (LINQ),是 C# 中一個強大的語言功能,可讓程式設計師針對各種資料來源建立清晰、具表現力的查詢。 本篇文章將討論 IronPDF(一個用於處理 PDF 文件的多功能 C# 函式庫)使用 LINQ 的 Distinct 函式。 我們將說明這種組合可能如何讓從集合中建立獨特文件的過程變得更容易。 在這篇文章中,我們將學習 C# LINQ distinct 函數與 IronPDF。
如何使用 C# LINQ Distinct 方法
1.建立一個新的主控台專案。 2.導入 System.Linq 命名空間。 3.建立包含多項目的清單。 4.從 List 中呼叫 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 ClassIronPDF。
程式設計師可借助 .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 ClassIronPDF。 的特點
- 將 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 方法。當您需要在 IronPDF 的 PDF 產生過程中定義決定唯一性的特定標準時,這將非常有用。
使用 IronPDF 的 LINQ 有什麼好處?
將 LINQ 與 IronPDF 搭配使用,可讓開發人員在資料處理的基礎上,建立獨特且有效率的 PDF 文件。它增強了程式碼的可讀性和效能,尤其是在管理大規模的文件產生任務時。
LINQ 的 Distinct 方法如何增強 PDF 文件的建立?
LINQ 的 Distinct 方法可確保最終輸出中僅包含唯一的項目,從而增強 PDF 文件的創建。此方法可與 IronPDF 配合使用,為各種資料類別產生獨特的 PDF 文件。
使用 IronPDF 時,是否可以自訂 PDF 輸出?
是的,IronPDF 提供了各種自訂 PDF 輸出的選項,包括設定頁面大小、邊界,以及新增頁首或頁尾。此自訂功能可與 LINQ 結合,以建立量身打造的獨特文件輸出。
在 PDF 中使用 LINQ 的 Distinct 方法可以從哪些場合獲益?
在 PDF 中使用 LINQ 的 Distinct 方法,可以使生成報告、發票或任何需要資料集唯一性的文件等場景獲益。利用 IronPDF 可以有效地產生乾淨且獨特的 PDF 輸出。
LINQ 如何提高資料驅動的 PDF 應用程式的效率?
LINQ 透過允許開發人員在產生 PDF 之前過濾和處理資料集,提高了資料驅動的 PDF 應用程式的效率。這可確保 PDF 中只包含必要且獨特的資料,進而優化效能與資源使用。







