.NET 帮助

C# LINQ 连接查询语法(开发人员如何使用)

发布 2024年二月18日
分享:

在多功能的 C# 编程中,LINQ (语言综合查询) LINQ 是查询和操作对象集合的强大工具。在 LINQ 提供的众多操作符中,Join 操作符是合并来自多个来源的数据的关键操作符。

在本文中,我们将深入探讨 Join 操作符的复杂性。 C# LINQ 连接运算符,揭开其功能、语法和实际应用的神秘面纱。

了解连接条款的基本原理

LINQ Join 操作符的核心是根据指定条件将两个或多个集合中的元素组合起来。该操作符使开发人员能够在内存集合上执行类似于 SQL 的连接,从而轻松合并来自不同来源的数据。

LINQ 连接操作符的语法

LINQ 连接操作符的语法具有很强的表现力,其模式类似于 SQL 连接。基本语法如下

var queryResult = 
    from element1 in collection1
    join element2 in collection2 on element1.Key equals element2.Key
    select new { element1, element2 };
var queryResult = 
    from element1 in collection1
    join element2 in collection2 on element1.Key equals element2.Key
    select new { element1, element2 };
Dim queryResult = From element1 In collection1
	Join element2 In collection2 On element1.Key Equals element2.Key
	Select New With {
		Key element1,
		Key element2
	}
VB   C#

在此语法中

  • element1element2 是变量,分别代表 collection1collection2 中的元素。
  • element1.Keyelement2.Key 是作为连接操作基础的属性。
  • equals 关键字指定了连接的条件。
  • select 子句创建一个新对象,将两个集合中的元素组合在一起。

LINQ 连接类型

LINQ 支持几种类型的连接,包括

  1. Inner Join: 只返回两个集合中具有匹配键的元素。
var innerJoin = from customer in customers
                    join order in orders on customer.CustomerID equals order.CustomerID // join orders to customers based on the customer ID key
                    select new { customer.CustomerID, customer.CustomerName, order.OrderID }; // create a new anonymous object based on the objects obtained from the join
var innerJoin = from customer in customers
                    join order in orders on customer.CustomerID equals order.CustomerID // join orders to customers based on the customer ID key
                    select new { customer.CustomerID, customer.CustomerName, order.OrderID }; // create a new anonymous object based on the objects obtained from the join
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#
  1. 左外连接 (默认值): 返回左侧集合的所有元素和右侧集合的匹配元素。如果找不到匹配元素,结果将包含右侧元素的默认值。
var leftOuterJoin = from customer in customers
                        join order in orders on customer.CustomerID equals order.CustomerID into customerOrders
                        from co in customerOrders.DefaultIfEmpty()
                        select new { customer.CustomerID, customer.CustomerName, OrderID = co?.OrderID ?? -1 };
var leftOuterJoin = from customer in customers
                        join order in orders on customer.CustomerID equals order.CustomerID into customerOrders
                        from co in customerOrders.DefaultIfEmpty()
                        select new { customer.CustomerID, customer.CustomerName, OrderID = co?.OrderID ?? -1 };
Dim leftOuterJoin = From customer In customers
	Group Join order In orders On customer.CustomerID Equals order.CustomerID Into customerOrders = Group
	From co In customerOrders.DefaultIfEmpty()
	Select New With {
		Key customer.CustomerID,
		Key customer.CustomerName,
		Key .OrderID = If(co?.OrderID, -1)
	}
VB   C#
  1. 分组连接: 将左侧集合中的元素与右侧集合中的匹配元素进行分组。
var groupJoin = from customer in customers
                    join order in orders on customer.CustomerID equals order.CustomerID into customerOrders
                    select new { customer.CustomerID, customer.CustomerName, Orders = customerOrders };
var groupJoin = from customer in customers
                    join order in orders on customer.CustomerID equals order.CustomerID into customerOrders
                    select new { customer.CustomerID, customer.CustomerName, Orders = customerOrders };
Dim groupJoin = From customer In customers
	Group Join order In orders On customer.CustomerID Equals order.CustomerID Into customerOrders = Group
	Select New With {
		Key customer.CustomerID,
		Key customer.CustomerName,
		Key .Orders = customerOrders
	}
VB   C#

现实世界的应用:合并客户和订单数据

让我们考虑一个实际例子,我们有两个集合: 客户和订单**。我们希望使用 LINQ Join 操作符创建一个结果集,将客户信息与相应的订单结合起来。

var customerOrderInfo = 
    from customer in customers
    join order in orders on customer.CustomerID equals order.CustomerID
    select new { customer.CustomerID, customer.CustomerName, order.OrderID, order.OrderDate };
var customerOrderInfo = 
    from customer in customers
    join order in orders on customer.CustomerID equals order.CustomerID
    select new { customer.CustomerID, customer.CustomerName, order.OrderID, order.OrderDate };
Dim customerOrderInfo = From customer In customers
	Join order In orders On customer.CustomerID Equals order.CustomerID
	Select New With {
		Key customer.CustomerID,
		Key customer.CustomerName,
		Key order.OrderID,
		Key order.OrderDate
	}
VB   C#

在本例中,结果集将包含客户信息条目及其相关订单。join 扩展方法语法可帮助 C# 开发人员执行类似 SQL 的连接操作。

IronPDF 简介

C# LINQ 连接查询语法(如何为开发人员工作):图 1 - IronPDF 网页

IronPDF 是一个全面的 C# 库,设计用于创建、处理和编辑 PDF 文档。它使开发人员能够从各种数据源动态生成 PDF,使其成为需要生成 PDF 文档的应用程序的多功能解决方案。

安装 IronPDF:快速入门

要开始在 C# 项目中使用 IronPDF 库,可以轻松安装 IronPDF NuGet 软件包。在软件包管理器控制台中使用以下命令:

Install-Package IronPdf

或者,您也可以在 NuGet 软件包管理器中搜索 "IronPDF",然后安装。

C# LINQ 连接查询语法(开发人员如何使用):图 2 - 从 NuGet 软件包管理器安装 IronPDF 库

LINQ Join 和 IronPDF:动态二重奏?

LINQ Join 操作符以其合并不同来源数据的能力而闻名,在数据集成是关键的情况下,它可以成为宝贵的资产。在使用 IronPDF 的 LINQ Join 时,首要考虑的是要集成到 PDF 文档中的数据的性质。

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

情景 1:在生成 PDF 之前合并数据

如果您的目标是在启动 PDF 生成流程之前合并来自不同数据源的数据,那么可以单独使用 LINQ Join。一旦有了统一的数据集,就可以利用 IronPDF 根据集成数据动态生成 PDF 文档。

下面是一个简化的示例:

// Assume 'customerOrderInfo' is a result set obtained using LINQ Join
var pdfDocument = new IronPdf.ChromePdfRenderer();
foreach (var entry in query)
{
    // Use IronPDF to add content to the PDF based on integrated data
    pdfDocument.AddHTML($"<p>Customer ID: {entry.CustomerID}, Order ID: {entry.OrderID}</p>");
}
// Save or render the PDF document as needed
pdfDocument.SaveAs("IntegratedDataDocument.pdf");
// Assume 'customerOrderInfo' is a result set obtained using LINQ Join
var pdfDocument = new IronPdf.ChromePdfRenderer();
foreach (var entry in query)
{
    // Use IronPDF to add content to the PDF based on integrated data
    pdfDocument.AddHTML($"<p>Customer ID: {entry.CustomerID}, Order ID: {entry.OrderID}</p>");
}
// Save or render the PDF document as needed
pdfDocument.SaveAs("IntegratedDataDocument.pdf");
' Assume 'customerOrderInfo' is a result set obtained using LINQ Join
Dim pdfDocument = New IronPdf.ChromePdfRenderer()
For Each entry In query
	' Use IronPDF to add content to the PDF based on integrated data
	pdfDocument.AddHTML($"<p>Customer ID: {entry.CustomerID}, Order ID: {entry.OrderID}</p>")
Next entry
' Save or render the PDF document as needed
pdfDocument.SaveAs("IntegratedDataDocument.pdf")
VB   C#

探索生成 PDF 文档的更多方法,以及如何将 LINQ Join 与 IronPDF 结合使用,请访问 文件 page.

情景 2:PDF 生成过程中的动态数据集成

IronPDF 允许在 PDF 文档中添加动态内容,这使得在 PDF 生成过程中使用 LINQ Join 集成数据成为可能。在这里,我们将创建客户类并对其进行排序,以表示真实世界中的应用。数据源可以是 SQL 数据库或某种结构化格式,在本例中,数据源是包含一组数据属性的对象列表,就像数据库中的表格一样。下面的示例展示了 LINQ Join 方法与 IronPDF 的详细集成,我们使用了 HTML 字符串 来生成文件:

using System;
using System.Collections.Generic;
using System.Linq;
using IronPdf;
class Order
{
    public int OrderID { get; set; }
    public int CustomerID { get; set; }
    // Other order-related properties...
}
class Customer
{
    public int CustomerID { get; set; }
    // Other customer-related properties...
}
class Program
{
    static void Main()
    {
        // Sample orders collection
        var orders = new List<Order>
        {
            new Order { OrderID = 1, CustomerID = 1 },
            new Order { OrderID = 2, CustomerID = 1 },
            new Order { OrderID = 3, CustomerID = 2 },
        };
        // Sample customers collection
        var customers = new List<Customer>
        {
            new Customer { CustomerID = 1 },
            new Customer { CustomerID = 2 },
        };
        var pdfDocument = new ChromePdfRenderer();
        string htmlContent = "<h1>Details generated using LINQ JOIN</h1>";
    // Use join to find customer orders
    var query = from customer in customers
                     join order in orders on customer.CustomerID equals order.CustomerID
                     select new { CustomerID = customer.CustomerID, OrderID = order.OrderID };
    foreach (var result in query)
    {
            // Use IronPDF to dynamically add content to the PDF based on integrated data
            htmlContent += $"<p>Customer ID: {result.CustomerID}, Order ID: {result.OrderID}</p>";
    }
    // Save or render the PDF document as needed
    pdfDocument.RenderHtmlAsPdf(htmlContent)
    .SaveAs("DynamicIntegratedDataDocument.pdf");
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using IronPdf;
class Order
{
    public int OrderID { get; set; }
    public int CustomerID { get; set; }
    // Other order-related properties...
}
class Customer
{
    public int CustomerID { get; set; }
    // Other customer-related properties...
}
class Program
{
    static void Main()
    {
        // Sample orders collection
        var orders = new List<Order>
        {
            new Order { OrderID = 1, CustomerID = 1 },
            new Order { OrderID = 2, CustomerID = 1 },
            new Order { OrderID = 3, CustomerID = 2 },
        };
        // Sample customers collection
        var customers = new List<Customer>
        {
            new Customer { CustomerID = 1 },
            new Customer { CustomerID = 2 },
        };
        var pdfDocument = new ChromePdfRenderer();
        string htmlContent = "<h1>Details generated using LINQ JOIN</h1>";
    // Use join to find customer orders
    var query = from customer in customers
                     join order in orders on customer.CustomerID equals order.CustomerID
                     select new { CustomerID = customer.CustomerID, OrderID = order.OrderID };
    foreach (var result in query)
    {
            // Use IronPDF to dynamically add content to the PDF based on integrated data
            htmlContent += $"<p>Customer ID: {result.CustomerID}, Order ID: {result.OrderID}</p>";
    }
    // Save or render the PDF document as needed
    pdfDocument.RenderHtmlAsPdf(htmlContent)
    .SaveAs("DynamicIntegratedDataDocument.pdf");
    }
}
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports IronPdf
Friend Class Order
	Public Property OrderID() As Integer
	Public Property CustomerID() As Integer
	' Other order-related properties...
End Class
Friend Class Customer
	Public Property CustomerID() As Integer
	' Other customer-related properties...
End Class
Friend Class Program
	Shared Sub Main()
		' Sample orders collection
		Dim orders = New List(Of Order) From {
			New Order With {
				.OrderID = 1,
				.CustomerID = 1
			},
			New Order With {
				.OrderID = 2,
				.CustomerID = 1
			},
			New Order With {
				.OrderID = 3,
				.CustomerID = 2
			}
		}
		' Sample customers collection
		Dim customers = New List(Of Customer) From {
			New Customer With {.CustomerID = 1},
			New Customer With {.CustomerID = 2}
		}
		Dim pdfDocument = New ChromePdfRenderer()
		Dim htmlContent As String = "<h1>Details generated using LINQ JOIN</h1>"
	' Use join to find customer orders
	Dim query = From customer In customers
		Join order In orders On customer.CustomerID Equals order.CustomerID
		Select New With {
			Key .CustomerID = customer.CustomerID,
			Key .OrderID = order.OrderID
		}
	For Each result In query
			' Use IronPDF to dynamically add content to the PDF based on integrated data
			htmlContent &= $"<p>Customer ID: {result.CustomerID}, Order ID: {result.OrderID}</p>"
	Next result
	' Save or render the PDF document as needed
	pdfDocument.RenderHtmlAsPdf(htmlContent).SaveAs("DynamicIntegratedDataDocument.pdf")
	End Sub
End Class
VB   C#

该代码使用了join关键字,可帮助查找每个客户的匹配订单,使查询更简洁、更具表现力。

C# LINQ 连接查询语法(开发人员如何使用):图 3 - 上一代码示例的 PDF 输出结果

结论

总之,IronPDF 是在 C# 应用程序中生成 PDF 的强大解决方案。当与强大的 LINQ Join 运算符相结合时,开发人员可以在 PDF 生成过程之前或期间实现无缝数据集成。无论您是需要将客户信息与订单相结合,还是需要合并来自不同来源的数据,LINQ Join 和 IronPDF 这对动态组合都能为您提供灵活高效的方法,增强您在 C# 应用程序中生成 PDF 的能力。

总之,C# LINQ Join 操作符是无缝集成多种来源数据的强大工具。无论您处理的是数据库、API 响应还是内存集合,LINQ Join 操作符都能简化根据指定条件组合数据的过程。当您在 C# 应用程序中浏览多样化的数据连接时,请考虑一下 LINQ Join 操作符为您的数据集成工具包带来的强大功能和灵活性。掌握该操作符将为高效处理和操作数据开辟新的可能性,从而增强 C# 应用程序的功能。

IronPDF 提供了 免费试用 以测试其全部功能。不过,它需要 许可 试用期一过,您就可以继续使用。

< 前一页
C# 密封类(开发人员使用指南)
下一步 >
C# String.Format(开发人员如何使用)

准备开始了吗? 版本: 2024.9 刚刚发布

免费NuGet下载 总下载量: 10,746,704 查看许可证 >