IRONSOFTWAREHOME
開發者更新

C# LINQ Distinct (對開發者如何運作)

Jacob Mellor,首席技術官 @ Team Iron
Jacob Mellor
Updated: 2026年4月21日

C#中的語言整合查詢(LINQ)是一個強大的語言功能,使程式設計師能夠為各種資料源建立清晰、表達的查詢。 本文將討論如何使用IronPDF這個多功能的C#程式庫與LINQ的Distinct功能來處理PDF文件。 我們將展示這種組合如何使從集合中建立唯一文件的過程變得更簡單。 在這篇文章中,我們將學習如何在IronPDF中使用C# LINQ的distinct功能。

如何使用C#LINQ Distinct方法

  1. 建立一個新的控制台專案。
  2. 引入System.Linq命名空間。
  3. 建立一個包含多個項目的清單。
  4. 從清單中調用Distinct()方法。
  5. 獲取唯一值並在控制台上顯示結果。
  6. 處理所有建立的物件。

什麼是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);
        }
    }
}

自定義相等比較器

您可以通過使用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}");
        }
    }
}

使用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);
        }
    }
}

使用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}");
        }
    }
}

按特定屬性區分

在處理物件時,您可以建立自己的邏輯來辨別特定屬性,或者利用從第三方庫(如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}");
        }
    }
}

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");
    }
}

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包管理器控制台中輸入以下程式碼以完成此操作:

PM > Install-Package IronPdf

C# LINQ Distinct (How It Works For Developers): Figure 1 - To install the IronPDF library using the NuGet Package Manager Console, enter the following command: "Install IronPDF" or ".NET add package IronPDF"

使用NuGet包管理器來搜索名為"IronPDF"的包是一個附加選項。我們可以從與IronPDF相關的所有NuGet包中選擇並下載所需的包。

C# LINQ Distinct (How It Works For Developers): Figure 2 - To install the IronPDF library using the NuGet Package Manager, search for the package "IronPDF" in the Browse tab and choose the latest version of IronPDF package to download and install in your project.

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}");
    }
}

在這個例子中,使用Distinct方法為類別集合獲取一系列獨特的類別。 它有助於從序列中刪除重複元素。 接下來,使用IronPDF建立具有這些唯一元素的PDF文件。 該方法保證僅為唯一類別生產單獨的PDF文件。

控制台輸出

C# LINQ Distinct(開發者如何使用):圖3 - 控制台輸出

生成的PDF輸出

C# LINQ Distinct(開發者如何使用):圖4 - PDF輸出:技術報告

要了解更多有關使用HTML生成PDF的IronPDF程式碼範例,請參閱IronPDF HTML到PDF範例程式碼。

結論

LINQ的Distinct擴展方法與IronPDF結合提供了一個強大而高效的機制,用於基於值建立獨特的PDF文件。 無論您是處理分類、標籤或任何其他需要單獨文件的資料,此方法簡化了程式碼並保證高效的文件生成。

您可以通過利用LINQ進行資料處理和IronPDF進行文件生成,開發出一個可靠的和表達性的解決方案來管理您的C#應用程式的不同方面。 在為您的項目使用這些策略時,請記住您應用程式的特定需求並調整實作以實現最大的可靠性和性能。

Jacob Mellor,首席技術官 @ Team Iron
首席技術官

Jacob Mellor是Iron Software的首席技術官,一位在C# PDF技術上開創先河的遠見工程師。作為Iron Software核心程式碼庫的原開發者,他從創立以來就一直在塑造公司的產品架構,與首席執行官Cameron Rimington一起將公司轉變為服務於NASA、特斯拉和全球政府公司的50多名人員的公司。

...
閱讀更多

相關文章

Key in blue circle

立即免費取得 30 天試用金鑰。

Your trial license will be sent to your email address

無任何限制。100% 解鎖。無需信用卡。

OR
bullet_checked無需信用卡或建立帳號無任何限制。100% 解鎖。無需信用卡。
  • Logo Aetna
  • Logo NASA
  • Logo GE
  • Logo Porsche
  • Logo USDA
  • Logo Qatar
Join Millions of Engineers who’ve tried Iron Suite
預訂您的免費現場演示
Booking Badge

受到全球數百萬工程師的信任

Iron Software的客戶標誌
獲取您的無義務諮詢
填寫以下表格或電子郵件sales@ironsoftware.com
您的詳細資訊將始終保密。
受到全球數百萬工程師的信任
Iron Software的客戶標誌
立即獲取您的30天試用金鑰。
無需信用卡或帳戶建立
C# 用於PDF的NuGet程式庫
使用NuGet安裝

版本: 2026.9

PM > Install-Package IronPdf
nuget.org/packages/IronPdf/
  1. 在解決方案資源管理器,右鍵點選參考,管理NuGet包
  2. 選擇瀏覽並搜尋"IronPdf"
  3. 選擇套件並安裝
C# PDF DLL
下載DLL

版本: 2026.9

或者點擊此處下載Windows安裝程式。

  1. 下載並解壓IronPDF到類似~/Libs的位置,位於您的解決方案目錄中
  2. 在Visual Studio解決方案資源管理器,右鍵點選參考。選擇瀏覽,"IronPdf.dll"

授權從$999起