.NET 帮助

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

发布 2024年二月18日
分享:

在多功能的 C# 编程中,LINQ(语言综合查询)作为查询和操作对象集合的强大工具,".NET "和 "Node.js "在翻译中脱颖而出。 在 LINQ 提供的众多操作符中,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. 内部连接: 仅返回两个集合中具有匹配键的元素。
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 开发 PDF 解决方案是一个综合性 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 结合使用,请访问IronPDF 文档.

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

IronPdf 允许在 PDF 文档中添加动态内容,使得在 PDF 生成过程中使用 LINQ Join 集成数据成为可能。 在此,我们将创建并订购客户类,以表示真实世界的应用。 数据源可以是 SQL 数据库或某种结构化格式,在本例中,数据源可以是包含一组数据属性的对象列表,就像数据库中的表格一样。 下面的示例展示了 LINQ Join 方法与 IronPDF 的详细集成,我们使用了用于生成 PDF 的 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.12 刚刚发布

免费NuGet下载 总下载量: 11,781,565 查看许可证 >