.NET 幫助

C# LINQ Join 查詢語法(對開發者的工作原理)

發佈 2024年2月18日
分享:

在 C# 程式設計的多樣性中,LINQ (語言集成查詢) 在查詢和操作對象集合方面,脫穎而出。LINQ 提供了眾多運算符,其中 Join 運算符在合併多個來源的數據時起著關鍵作用。

在本文中,我們將深入探討 C# LINQ Join 操作符,揭示其功能、語法和實際應用。

了解聯接子句的基礎知識

在其核心,LINQ Join 運算符旨在根據指定的條件結合來自兩個或多個集合的元素。這個運算符讓開發人員能夠在內存集合上執行類似 SQL 的聯接,從而輕鬆地合併來自不同來源的數據。

LINQ Join 運算子的語法

LINQ Join 運算子的語法表達力強,遵循與 SQL join 類似的模式。基本語法如下:

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#

真實應用:合併客戶和訂單數據

讓我們考慮一個實際範例,我們有兩個集合:customersorders。我們希望使用 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 的 join 操作。

介紹 IronPDF

C# LINQ Join 查詢語法(開發人員如何使用):圖1 - IronPDF 網頁

IronPDF 是一個全面的 C# 函式庫,專門用於創建、處理和編輯 PDF 文件。它使開發人員能夠從各種資料來源動態生成 PDF,因此它是需要生成 PDF 文件的應用程式的多功能解決方案。

安裝IronPDF:快速入門

要在您的C#專案中開始使用IronPDF庫,您可以輕鬆安裝IronPDF NuGet套件。在您的套件管理器控制台中使用以下命令:

Install-Package IronPdf

或者,您可以在 NuGet 套件管理器中搜索 "IronPDF" 並從那裡安裝。

C# LINQ Join 查詢語法(開發者用法):圖2 - 從NuGet包管理器安裝IronPDF庫

LINQ Join 和 IronPDF:動態雙雄?

LINQ Join 操作符因其能夠合併來自不同來源的數據而聞名,可在數據整合至關重要的情況下成為寶貴的資產。在將 LINQ Join 與 IronPDF 一起使用時,主要考慮的是你打算整合到 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,請訪問 文檔 頁面。

情境二:在 PDF 生成過程中整合動態數據

IronPDF 允許在 PDF 文檔中添加動態內容,使得在 PDF 生成過程中可以使用 LINQ Join 來整合數據。在這裡,我們將創建和訂單客戶類,以代表實際應用程式。數據源可以是 SQL 數據庫或一些結構化格式,在此情況下,數據源是一組包含數據屬性的對象列表,就像數據庫中的表一樣。以下示例詳細展示了如何使用 IronPDF 集成 LINQ Join 方法。 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# 字串格式化(開發者使用說明)

準備開始了嗎? 版本: 2024.9 剛剛發布

免費 NuGet 下載 總下載次數: 10,808,842 查看許可證 >