C# LINQ Distinct (對開發者如何運作)
C#中的語言整合查詢(LINQ)是一個強大的語言功能,使程式設計師能夠為各種資料源建立清晰、表達的查詢。 本文將討論如何使用IronPDF這個多功能的C#程式庫與LINQ的Distinct功能來處理PDF文件。 我們將展示這種組合如何使從集合中建立唯一文件的過程變得更簡單。 在這篇文章中,我們將學習如何在IronPDF中使用C# LINQ的distinct功能。
如何使用C#LINQ Distinct方法
- 建立一個新的控制台專案。
- 引入
System.Linq命名空間。 - 建立一個包含多個項目的清單。
- 從清單中調用
Distinct()方法。 - 獲取唯一值並在控制台上顯示結果。
- 處理所有建立的物件。
什麼是LINQ
開發者可以在他們的程式碼中直接使用C#的LINQ(語言整合查詢)功能來構建清晰的資料操作查詢。 LINQ首次包含在.NET Framework 3.5中,提供了一種用於查詢範圍資料源(包括資料庫和集合)的標準語法。 LINQ通過使用像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與值型別
使用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與匿名型別
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包管理器控制台中輸入以下程式碼以完成此操作:
Install-Package IronPdf

使用NuGet包管理器來搜索名為"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輸出

要了解更多有關使用HTML生成PDF的IronPDF程式碼範例,請參閱IronPDF HTML到PDF範例程式碼。
結論
LINQ的Distinct擴展方法與IronPDF結合提供了一個強大而高效的機制,用於基於值建立獨特的PDF文件。 無論您是處理分類、標籤或任何其他需要單獨文件的資料,此方法簡化了程式碼並保證高效的文件生成。
您可以通過利用LINQ進行資料處理和IronPDF進行文件生成,開發出一個可靠的和表達性的解決方案來管理您的C#應用程式的不同方面。 在為您的項目使用這些策略時,請記住您應用程式的特定需求並調整實作以實現最大的可靠性和性能。
常見問題
如何在C#中從集合中移除重複的項目?
您可以使用LINQ的Distinct方法從C#集合中移除重複的項目。此方法在與IronPDF結合使用時特別有用,可以從不同的資料類別中生成獨特的PDF文件。
如何將HTML轉換為C#中的PDF?
要在C#中將HTML轉換為PDF,您可以使用IronPDF的RenderHtmlAsPdf方法。這使您可以有效地將HTML字串或文件轉換為PDF文件。
我可以用LINQ的Distinct方法來處理自定義物件嗎?
是的,您可以通過提供自定義的相等比較器來使用LINQ的Distinct方法處理自定義物件。這在您需要為IronPDF生成過程中確定PDF獨特性的特定標準時特別有用。
使用LINQ與IronPDF有何好處?
使用LINQ與IronPDF讓開發者可以根據資料處理建立獨特且高效的PDF文件。尤其是在管理大規模文件生成任務時,它能提升程式碼可讀性和效能。
LINQ的Distinct方法如何增強PDF文件建立?
LINQ的Distinct方法可以通過確保只有獨特的項目被包含在最終輸出中來增強PDF文件的建立。此方法可與IronPDF結合使用,以生成不同資料類別的獨特PDF文件。
使用IronPDF時可以自定義PDF輸出嗎?
可以,IronPDF提供各種選項來自定義PDF輸出,包括設置頁面尺寸、邊距以及新增頁眉或頁腳。可以將這些自定義選項與LINQ結合使用來建立符合要求的獨特文件輸出。
哪些情境可以受益於將LINQ的Distinct方法與PDF結合使用?
如生成報告、發票或任何需要從資料集中獨特性要求的文件等情境,可以從使用LINQ的Distinct方法與PDF結合中受益。IronPDF可以高效產出乾淨且獨特的PDF文件。
LINQ如何提高以資料為導向的PDF應用程式效能?
LINQ讓開發者可以在生成PDF之前篩選和處理資料集,提高以資料為導向的PDF應用程式的效能。此操作確保PDF中只包含必要且獨特的資料,優化效能和資源使用。




