C# LINQ Distinct(开发人员如何使用)
集成查询语言(LINQ)是C#中的一项强大语言功能,使程序员能够为各种数据源创建清晰、富有表现力的查询。 这篇文章将讨论使用IronPDF与C#中用于处理PDF文档的多功能库的使用,并利用LINQ的Distinct功能。 我们将展示这种组合如何可以使从集合中创建独特文档的过程更简单。 在本文中,我们将学习C# LINQ distinct功能与IronPDF。
如何使用C# LINQ的Distinct方法
- 创建一个新的控制台项目。
- 导入
System.Linq命名空间。 - 创建一个包含多个项目的列表。
- 从列表中调用
Distinct()方法。 - 获取唯一值并在控制台上显示结果。
- 处理所有已创建的对象。
什么是LINQ
通过C#的LINQ(集成查询语言)功能,开发人员可以直接在代码中构建用于数据操作的清晰和富有表现力的查询。 首次在.NET Framework 3.5中引入,LINQ提供了一种用于查询多种数据源(包括数据库和集合)的标准语法。 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);
}
}
}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自定义相等比较器
您可以通过使用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}");
}
}
}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使用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);
}
}
}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使用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}");
}
}
}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通过特定属性来区分
在处理对象时,您可以自行创建区分某个属性的逻辑,或者可以使用第三方库(如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}");
}
}
}' 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 ClassIronPDF。
程序员可以使用C#语言创建、编辑和修改PDF文档,并借助.NET库IronPDF网站。 该程序提供了一系列工具和功能,以实现各种涉及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");
}
}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 ClassIronPDF。的功能
- 转换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

使用NuGet包管理器搜索包"IronPDF"是另一种选择。我们可以从这个列表中选择并下载与IronPDF相关的所有所需NuGet包。

LINQ与IronPDF
请考虑这样一种情况,您有一组数据,并希望根据该组中的不同值创建各种PDF文档。 当与IronPDF结合使用以快速创建文档时,这是LINQ的Distinct的有用之处,尤其是闪耀之处。
使用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}");
}
}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在此示例中,通过对类别集合使用Distinct方法获取一系列独特类别。 它有助于从序列中移除重复元素。 接下来,使用IronPDF创建包含这些唯一元素的PDF文档。 这种方法确保只为唯一类别生成单独的PDF文档。
控制台输出

生成的PDF输出

要了解有关为PDF使用HTML生成的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 结合使用来创建定制的独特文档输出。
哪些场景可以从使用 LINQ 的 Distinct 方法与 PDF 中受益?
生成报告、发票或任何需要数据集唯一性的文档等场景可以从使用 LINQ 的 Distinct 方法与 PDF 中受益。 IronPDF 可用于高效生成简洁且独特的 PDF 输出。
LINQ 如何提高数据驱动 PDF 应用程序的效率?
LINQ 通过允许开发人员在生成 PDF 之前过滤和操作数据集来提高数据驱动 PDF 应用程序的效率。这确保仅将必要且唯一的数据包含在 PDF 中,从而优化性能和资源使用。








