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);
}
}
}自訂等式比較器
您可以使用 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}");
}
}
}使用值類型的區別
在使用 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);
}
}
}使用匿名類型的區別
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}");
}
}
}以特定屬性區分
在處理物件時,您可以建立自己的邏輯來區分某個屬性,或是利用第三方函式庫 (如 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}");
}
}
}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");
}
}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}");
}
}在這個範例中,透過使用 Distinct 方法來取得一系列不同的類別集合。 有助於移除序列中重複的元素。 接下來,IronPDF 會用這些獨特的元素來建立 PDF 文件。 此方法可保證只針對獨特的類別製作獨立的 PDF 文件。
控制台輸出

生成的 PDF 輸出

若要瞭解更多關於 IronPdf 使用 HTML 產生 PDF 的程式碼範例,請參閱 IronPDF HTML to PDF 範例程式碼。
結論
LINQ 的 Distinct 延伸方法與 IronPDF 相結合,提供了一個強大且有效率的機制,可根據值建立獨特的 PDF 文件。 無論您是處理分類、標籤或任何其他需要獨立文件的資料,此方法都能簡化程式碼並保證有效的文件製作。
您可以利用 LINQ 進行資料處理,並利用 IronPDF 製作文件,開發出可靠且具表現力的解詴,以管理 C# 應用程式的不同方面。 在您的專案中使用這些策略時,請牢記您應用程式的特殊需求,並調整實作,以達到最高的可靠性和效能。
常見問題解答
如何在C#中刪除集合中的重複條目?
在 C# 中,您可以使用 LINQ 的Distinct方法來刪除集合中的重複條目。此方法與 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 結合使用,從而創建客製化的獨特文件輸出。
哪些場景適合使用 LINQ 的 Distinct 方法處理 PDF?
諸如產生報告、發票或任何需要從資料集中提取唯一值的文件等場景,都可以受益於將 LINQ 的Distinct方法應用於 PDF 處理。 IronPDF 可以有效率地產生清晰且獨特的 PDF 輸出。
LINQ 如何提高資料驅動 PDF 應用程式的效率?
LINQ 讓開發人員在產生 PDF 之前篩選和處理資料集,從而提高資料驅動型 PDF 應用程式的效率。這確保 PDF 中僅包含必要且唯一的數據,從而優化效能和資源利用率。







