.NET HELP

C# LINQ Distinct (How It Works For Developers)

Published February 18, 2024
Share:

Introduction

Language-integrated query (LINQ), a potent language feature in C#, enables programmers to create clear, expressive searches for a variety of data sources. This post will discuss the use of IronPDF, a versatile C# library for working with PDF documents, using LINQ's Distinct function. We will show how this combination may make the process of creating unique papers from a collection easier. In this article, we are going to learn about the C# LINQ distinct function with IronPDF.

How to Use C# LINQ Distinct Method

  1. Create a new console project.
  2. Import System.Linq namespace.
  3. Create a list with multiple items.
  4. Call the method Distinct() from the List.
  5. Get the unique values and display the result on the console.
  6. Dispose of all the created objects.

What is LINQ

Developers may build clear and expressive queries for data manipulation directly in their code with C#'s LINQ (Language Integrated Query) feature. LINQ, which was first included in the .NET Framework 3.5, offers a standard syntax for querying a range of data sources, including databases and collections. LINQ makes simple tasks like filtering and projection easier using operators like Where and Select, which improves code readability. Because it allows for postponed execution for optimal speed, this feature is crucial for C# developers to ensure that data manipulation operations are completed quickly and naturally in a manner analogous to SQL.

Understanding LINQ Distinct

Duplicate elements may be removed from a collection or sequence using LINQ's Distinct function. In the absence of a custom equality comparer, it compares items using their default comparer. This makes it a great option in situations when you need to work with a unique collection and remove duplicate components. The Distinct technique makes use of the Default equality comparison to evaluate values. It will return false for the particular property that is duplicate based on that it will display unique elements.

Basic Usage

To obtain distinct items, the simplest way to use it is to use the Distinct method directly on a collection.

var distinctNumbers = numbers.Distinct();
var distinctNumbers = numbers.Distinct();
Dim distinctNumbers = numbers.Distinct()
VB   C#

Custom Equality Comparer

You can define a custom equality comparison by using an overload of the Distinct function. This is helpful if you wish to compare items according to particular standards. Please refer to the following example:

var distinctPeople = people.Distinct(new PersonEqualityComparer());
var distinctPeople = people.Distinct(new PersonEqualityComparer());
Dim distinctPeople = people.Distinct(New PersonEqualityComparer())
VB   C#

Using Distinct with Value Types

You don't need to supply a custom equality comparison when using the Distinct method with value types.

var distinctIntegers = integers.Distinct();
var distinctIntegers = integers.Distinct();
Dim distinctIntegers = integers.Distinct()
VB   C#

Using Distinct with Anonymous Types

Distinct may be used with anonymous types to remove duplicates based on particular attributes. Please refer to the following example:

var distinctPeople = people
    .Select(p => new { p.FirstName, p.LastName })
    .Distinct();
var distinctPeople = people
    .Select(p => new { p.FirstName, p.LastName })
    .Distinct();
Dim distinctPeople = people.Select(Function(p) New With {
	Key p.FirstName,
	Key p.LastName
}).Distinct()
VB   C#

Distinct by a Specific Property

When working with objects, you may either create your logic for distinguishing by a certain attribute, or you can utilize the DistinctBy extension method from third-party libraries (like More LINQ).

var distinctPeople = people.DistinctBy(p => p.Id);
var distinctPeople = people.DistinctBy(p => p.Id);
Dim distinctPeople = people.DistinctBy(Function(p) p.Id)
VB   C#

IronPDF

Programmers may create, edit, and alter PDF documents using the C# language with the aid of the .NET library IronPDF Website. The program provides a range of tools and functionalities to enable various tasks involving PDF files, such as generating PDFs from HTML, converting HTML to PDF, merging or splitting PDF documents, and adding text, images, and annotations to already existing PDFs. To know more about IronPDF, please refer to their IronPDF Documentation.

The main feature of IronPDF is HTML to PDF Conversion, which keeps your layouts and styles intact. You can generate PDFs from web content, perfect for reports, invoices, and documentation. It supports converting HTML files, URLs, and HTML strings to PDF files.

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
VB   C#

Features of IronPDF

  • Convert HTML to PDF: You may use IronPDF to convert any kind of HTML data—including files, URLs, and strings of HTML code—into PDF documents.
  • PDF Generation: Text, images, and other elements may be programmatically added to PDF documents using the C# programming language.
  • PDF Manipulation: IronPDF can split a PDF file into many files, merge several PDF documents into one file, and edit PDFs that already exist.
  • PDF Forms: Because the library enables users to build and fill PDF forms, it is useful in scenarios where form data needs to be gathered and processed.
  • Security Features: IronPDF may be used to encrypt PDF documents and provide password and permission protection.
  • Text Extraction: Text from PDF files may be extracted using IronPDF.

Install IronPDF

Get the IronPDF library; it's needed for the future patch. Enter the following code into the NuGet Package Manager Console to accomplish this:

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

Using the NuGet Package Manager to search for the package "IronPDF" is an additional choice. We may choose and download the necessary package from this list out of all the NuGet packages associated with IronPDF.

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 With IronPDF

Consider a situation in which you have a set of data and you wish to create various PDF documents according to different values in that set. This is where the usefulness of LINQ's Distinct shines, particularly when used with IronPDF to create documents quickly.

Generating Distinct PDFs with LINQ and IronPDF

using IronPdf;
using System;
using System.Collections.Generic;
using System.Linq;
public class DocumentGenerator
{
    public string result {get;set;}
    public int id {get;set;}
    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
        // distinct query syntax
        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 string result {get;set;}
    public int id {get;set;}
    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
        // distinct query syntax
        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 Property result() As String
	Public Property id() As Integer
	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
		' distinct query syntax
		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
VB   C#

In this example, a series of distinct categories are obtained by using the Distinct method for the categories collection. It will help us to remove duplicate elements from a sequence. Next, IronPDF is used to create a PDF document with unique elements. This method guarantees that separate PDF documents are produced solely for unique categories.

Console OUTPUT

C# LINQ Distinct (How It Works For Developers): Figure 3 - Console Output

Generated PDF Output

C# LINQ Distinct (How It Works For Developers): Figure 4 - PDF Output: Technology Report

To know more about the IronPDF code example for generating PDFs using HTML refer to the IronPDF HTML to PDF Example Code.

Conclusion

LINQ's Distinct extension method in conjunction with IronPDF offers a robust and efficient mechanism for creating unique PDF documents based on values. This method streamlines the code and guarantees effective document production whether you are working with categories, tags, or any other data where separate documents are needed.

You may develop a reliable and expressive solution for managing different aspects of your C# applications by utilizing LINQ for data processing and IronPDF for document production. When using these strategies for your projects, keep in mind the particular needs of your application and adjust the implementation to achieve maximum dependability and performance.

< PREVIOUS
C# Internal (How It Works For Developers)
NEXT >
C# Priority Queue (How It Works For Developers)

Ready to get started? Version: 2024.12 just released

Free NuGet Download Total downloads: 11,622,374 View Licenses >