C# LINQ Distinct (How It Works For Developers)
Language-integrated query (LINQ), a potent language feature in C#, enables programmers to create clear, expressive queries 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 documents 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
- Create a new console project.
- Import
System.Linq
namespace. - Create a list with multiple items.
- Call the method
Distinct()
from the List. - Get the unique values and display the result on the console.
- 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. First included in the .NET Framework 3.5, LINQ 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 delayed 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 uses the default equality comparers to evaluate values. It will exclude duplicates to return only unique elements.
Basic Usage
To obtain distinct items, the simplest way to use it is to use the Distinct
method directly on a collection.
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
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:
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
Using Distinct with Value Types
You don't need to supply a custom equality comparison when using the Distinct
method with value types.
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
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:
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
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 MoreLINQ).
// 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
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
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: The library enables users to build and fill PDF forms, making it 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 setting up your project. Enter the following code into the NuGet Package Manager Console to accomplish this:
Install-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.
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 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
In this example, a series of distinct categories are obtained by using the Distinct
method for the categories collection. It helps to remove duplicate elements from a sequence. Next, IronPDF is used to create a PDF document with these unique elements. This method guarantees that separate PDF documents are produced solely for unique categories.
Console OUTPUT
Generated PDF Output
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.
Frequently Asked Questions
What is LINQ in C#?
LINQ (Language Integrated Query) in C# is a feature that allows developers to write expressive and clear queries for data manipulation directly in their code. It was introduced in the .NET Framework 3.5 and provides a standard syntax for querying various data sources.
How does the Distinct method work in LINQ?
The Distinct method in LINQ is used to remove duplicate elements from a collection or sequence. It utilizes default equality comparers to evaluate values and returns only the unique elements.
Can you use a custom equality comparer with LINQ's Distinct method?
Yes, you can define a custom equality comparer by using an overload of the Distinct function. This is useful when you need to compare items according to specific criteria.
What is IronPDF?
IronPDF is a .NET library that enables programmers to create, edit, and manipulate PDF documents using the C# language. It provides functionalities such as generating PDFs from HTML, converting HTML to PDF, and editing existing PDFs.
How do you install IronPDF?
To install IronPDF, you can use the NuGet Package Manager Console in Visual Studio and enter the command 'Install-Package IronPdf'. Alternatively, you can search for 'IronPDF' in the NuGet Package Manager and select the package to install.
How can LINQ’s Distinct be used with PDF generation?
LINQ's Distinct can be used for generating unique PDF documents based on distinct values from a data set, utilizing libraries for PDF manipulation. This approach is particularly useful for creating separate documents for unique categories or tags.
What are some features of a PDF library like IronPDF?
A PDF library may offer features like converting HTML to PDF, PDF generation, PDF manipulation, building and filling PDF forms, providing security features, and extracting text from PDF files.
Is it possible to use LINQ's Distinct with value types?
Yes, when using LINQ's Distinct method with value types, you do not need to provide a custom equality comparison. The method will automatically use the default equality comparers for value types.
Can you use the Distinct method with anonymous types?
Yes, the Distinct method can be used with anonymous types to remove duplicates based on specific attributes. This allows for flexibility when working with custom data structures.
What is the advantage of using LINQ with a PDF library?
The advantage of using LINQ with a PDF library is the ability to create unique and efficient PDF documents based on data processing. This combination enhances code readability and performance, particularly when managing document generation tasks.