.NET 幫助

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

發佈 2024年2月18日
分享:

在 C# 程式設計的多樣性中,LINQ(語言集成查詢)作為查詢和操作對象集合的強大工具而脫穎而出。 在 LINQ 提供的眾多運算子中,Join 運算子是合併多個來源數據時的一個關鍵角色。

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

理解加入子句的基礎知識

LINQ Join 運算子從根本上是為了根據指定條件結合兩個或多個集合中的元素而設計的。 此运算符使开发者能够在内存集合上执行类似 SQL 的联接,轻松合并来自不同来源的数据。

LINQ Join 運算子的語法

LINQ Join 運算符的語法富有表達性,並遵循類似於 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#

實際應用:結合客戶和訂單信息

讓我們考慮一個實際的例子,其中我們有兩個集合: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#

在此範例中,結果集將包含具有客戶資訊的條目以及他們相關的訂單。 聯接擴展方法語法幫助 C# 開發人員執行類似 SQL 的聯接操作。

介紹 IronPDF

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

使用 IronPDF 開發 PDF 解決方案是一個全面的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,請訪問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# 字串格式化(開發者使用說明)

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

免費 NuGet 下載 總下載次數: 11,622,374 查看許可證 >