跳過到頁腳內容
.NET幫助

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

語言整合查詢 (LINQ) 是 C# 中的一項強大的語言特性,它使程式設計師能夠為各種資料來源創建清晰、富有表現力的查詢。 本文將討論如何使用IronPDF (一個功能強大的 C# 函式庫,用於處理 PDF 文件)以及LINQ 的 Distinct函數。 我們將展示這種組合如何使從集合中建立獨特文件的過程變得更加容易。 在本文中,我們將學習如何使用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 使用 WhereSelect 等運算符,使過濾和投影等簡單任務變得更容易,從而提高了程式碼的可讀性。 由於該特性允許延遲執行以獲得最佳速度,因此對於 C# 開發人員來說,該特性至關重要,它可以確保資料操作以類似於 SQL 的方式快速自然地完成。

理解 LINQ 的獨特之處

可以使用 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);
        }
    }
}
$vbLabelText   $csharpLabel

自訂相等性比較器

你可以使用 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}");
        }
    }
}
$vbLabelText   $csharpLabel

將 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);
        }
    }
}
$vbLabelText   $csharpLabel

將 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}");
        }
    }
}
$vbLabelText   $csharpLabel

具有特定屬性

在處理物件時,您可以建立自己的邏輯來透過某個屬性進行區分,或者您可以使用來自第三方程式庫(如 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}");
        }
    }
}
$vbLabelText   $csharpLabel

IronPDF

程式設計師可以使用 C# 語言使用.NET庫IronPDF網站建立、編輯和修改 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");
    }
}
$vbLabelText   $csharpLabel

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

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 dotnet 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}");
    }
}
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}");
    }
}
$vbLabelText   $csharpLabel

在這個例子中,透過使用 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# 應用程式的不同面向。 在專案中使用這些策略時,請牢記應用程式的特定需求,並調整實施方案以實現最大的可靠性和效能。

常見問題解答

如何移除 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 中僅包含必要且唯一的數據,從而優化性能和資源使用。

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

Jacob Mellor是Iron Software的首席技術官,也是開創C# PDF技術的前瞻性工程師。作為Iron Software核心代碼庫的原始開發者,他自公司成立以來就塑造了公司的產品架構,並與CEO Cameron Rimington將公司轉型為服務NASA、Tesla以及全球政府機構的50多人公司。

Jacob擁有曼徹斯特大學土木工程一級榮譽學士學位(1998年–2001年)。他於1999年在倫敦開立首家軟體公司,並於2005年建立了他的第一個.NET組件,專注於解決Microsoft生態系統中的複雜問題。

他的旗艦作品IronPDF和Iron Suite .NET程式庫全球已獲得超過3000萬次NuGet安裝,他的基礎代碼不斷在全球各地驅動開發者工具。擁有25年以上的商業經驗和41年的編碼專業知識,Jacob仍然專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

Iron Support Team

We're online 24 hours, 5 days a week.
Chat
Email
Call Me