跳過到頁腳內容
.NET幫助

C# Groupby(對於開發者的運行原理)

在 C# 中,GroupBy 方法是一個功能強大的工具,可根據指定的關鍵將資料來源中的元素組織成群組。 此方法是 LINQ(語言整合查詢)的一部分,可用於將項目依單一或多個屬性進行群組,對於資料分析與處理而言非常有價值。 GroupBy 方法簡化了複雜的資料作業,允許根據特定條件進行有效的資料組織和檢索。 我們將在這篇部落格中討論 GroupBy 和 IronPDF Library

GroupBy 的基本原理

GroupBy 方法的精髓在於它能夠根據指定的關鍵將給定集合的元素歸類為群組。 此關鍵屬性決定項目如何分組。 例如,您可以根據年齡關鍵值對學生清單進行分組,創建具有相同年齡的學生群組。 每個群組由一個關鍵值和共用該關鍵值的項目集合來表示。 關鍵屬性可以是任何物件,例如字串、數字,甚至是匿名物件,提供資料組合方式的彈性。

使用方法語法的 GroupBy

在 C# 中,應用 GroupBy 方法有兩種方式:方法語法和查詢語法。 方法語法使用 lambda 表達式定義群組鍵,是應用 GroupBy 操作的直接方法。

考慮以下範例,使用方法語法將學生清單依年齡分組:

using System;
using System.Collections.Generic;
using System.Linq;

public class Student
{
    public string Name { get; set; }
    public int Age { get; set; }
}

public class Program
{
    public static void Main()
    {
        List<Student> studentList = new List<Student>
        {
            new Student { Name = "Alice", Age = 20 },
            new Student { Name = "Bob", Age = 20 },
            new Student { Name = "Charlie", Age = 21 }
        };

        // Group students by their age using GroupBy
        var groupedResult = studentList.GroupBy(student => student.Age);

        foreach (var group in groupedResult)
        {
            Console.WriteLine($"Age Group: {group.Key}");

            foreach (var student in group)
            {
                Console.WriteLine($"Student Name: {student.Name}");
            }
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;

public class Student
{
    public string Name { get; set; }
    public int Age { get; set; }
}

public class Program
{
    public static void Main()
    {
        List<Student> studentList = new List<Student>
        {
            new Student { Name = "Alice", Age = 20 },
            new Student { Name = "Bob", Age = 20 },
            new Student { Name = "Charlie", Age = 21 }
        };

        // Group students by their age using GroupBy
        var groupedResult = studentList.GroupBy(student => student.Age);

        foreach (var group in groupedResult)
        {
            Console.WriteLine($"Age Group: {group.Key}");

            foreach (var student in group)
            {
                Console.WriteLine($"Student Name: {student.Name}");
            }
        }
    }
}
Imports System
Imports System.Collections.Generic
Imports System.Linq

Public Class Student
	Public Property Name() As String
	Public Property Age() As Integer
End Class

Public Class Program
	Public Shared Sub Main()
		Dim studentList As New List(Of Student) From {
			New Student With {
				.Name = "Alice",
				.Age = 20
			},
			New Student With {
				.Name = "Bob",
				.Age = 20
			},
			New Student With {
				.Name = "Charlie",
				.Age = 21
			}
		}

		' Group students by their age using GroupBy
		Dim groupedResult = studentList.GroupBy(Function(student) student.Age)

		For Each group In groupedResult
			Console.WriteLine($"Age Group: {group.Key}")

			For Each student In group
				Console.WriteLine($"Student Name: {student.Name}")
			Next student
		Next group
	End Sub
End Class
$vbLabelText   $csharpLabel

C# GroupBy (How It Works For Developers):圖 1 - 上一個程式碼範例的控制台輸出

LINQ GroupBy 方法使用 lambda 表達式按 Age 關鍵值對學生進行分組。 group.Key 代表年齡群組,內部的 foreach 循環會遍歷群組中的每個學生,並列印他們的姓名。

使用查詢語法的 GroupBy。

查詢語法提供更富表達力的方式來執行群組操作,類似 SQL 查詢。 在處理複雜的資料轉換和多個分組標準時尤其有用。 以下是如何使用查詢語法實現與前一範例相似的功能:

using System;
using System.Collections.Generic;
using System.Linq;

public static class Program
{
    public static void Main()
    {
        List<Student> studentList = new List<Student>
        {
            new Student { Name = "Alice", Age = 20 },
            new Student { Name = "Bob", Age = 20 },
            new Student { Name = "Charlie", Age = 21 }
        };

        // Group students by their age using query syntax
        var groupedResult = from student in studentList
                            group student by student.Age into ageGroup
                            select new { Age = ageGroup.Key, Students = ageGroup };

        foreach (var group in groupedResult)
        {
            Console.WriteLine($"Age Group: {group.Age}");

            foreach (var student in group.Students)
            {
                Console.WriteLine($"Student Name: {student.Name}");
            }
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;

public static class Program
{
    public static void Main()
    {
        List<Student> studentList = new List<Student>
        {
            new Student { Name = "Alice", Age = 20 },
            new Student { Name = "Bob", Age = 20 },
            new Student { Name = "Charlie", Age = 21 }
        };

        // Group students by their age using query syntax
        var groupedResult = from student in studentList
                            group student by student.Age into ageGroup
                            select new { Age = ageGroup.Key, Students = ageGroup };

        foreach (var group in groupedResult)
        {
            Console.WriteLine($"Age Group: {group.Age}");

            foreach (var student in group.Students)
            {
                Console.WriteLine($"Student Name: {student.Name}");
            }
        }
    }
}
Imports System
Imports System.Collections.Generic
Imports System.Linq

Public Module Program
	Public Sub Main()
		Dim studentList As New List(Of Student) From {
			New Student With {
				.Name = "Alice",
				.Age = 20
			},
			New Student With {
				.Name = "Bob",
				.Age = 20
			},
			New Student With {
				.Name = "Charlie",
				.Age = 21
			}
		}

		' Group students by their age using query syntax
		Dim groupedResult = From student In studentList
			Group student By student.Age Into ageGroup = Group
			Select New With {
				Key .Age = Age,
				Key .Students = ageGroup
			}

		For Each group In groupedResult
			Console.WriteLine($"Age Group: {group.Age}")

			For Each student In group.Students
				Console.WriteLine($"Student Name: {student.Name}")
			Next student
		Next group
	End Sub
End Module
$vbLabelText   $csharpLabel

在此片段中,查詢語法依 Age 將學生分組,類似於方法語法,但語法不同,有些人認為更易於閱讀。

透過多個鍵和屬性進行群組。

GroupBy 方法更進階的用途是透過多個鍵或屬性將資料分組。 此技術可根據多重值進行更詳細的資料分析與分類。 透過使用匿名物件或元组,您可以根據屬性的組合來將項目分組,為您的應用程式提供更豐富的資料結構。

範例:按姓名和年齡對學生進行分組。

考慮一種情況,您不僅需要根據年齡關鍵值對學生進行分組,還需要根據他們的姓名進行分組,以識別列表中具有相同姓名和年齡關鍵值的學生。這可以透過包含姓名和年齡的匿名類型進行分組。

using System;
using System.Collections.Generic;
using System.Linq;

public static class Program
{
    public static void Main()
    {
        List<Student> studentList = new List<Student>
        {
            new Student { Name = "Alice", Age = 20 },
            new Student { Name = "Alice", Age = 21 },
            new Student { Name = "Bob", Age = 20 },
            new Student { Name = "Charlie", Age = 21 }
        };

        // Group students by both Name and Age using an anonymous type as the key
        var groupedResult = studentList.GroupBy(student => new { student.Name, student.Age });

        foreach (var group in groupedResult)
        {
            Console.WriteLine($"Group Key: Name = {group.Key.Name}, Age = {group.Key.Age}");

            foreach (var student in group)
            {
                Console.WriteLine($"Student Name: {student.Name}, Age: {student.Age}");
            }
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;

public static class Program
{
    public static void Main()
    {
        List<Student> studentList = new List<Student>
        {
            new Student { Name = "Alice", Age = 20 },
            new Student { Name = "Alice", Age = 21 },
            new Student { Name = "Bob", Age = 20 },
            new Student { Name = "Charlie", Age = 21 }
        };

        // Group students by both Name and Age using an anonymous type as the key
        var groupedResult = studentList.GroupBy(student => new { student.Name, student.Age });

        foreach (var group in groupedResult)
        {
            Console.WriteLine($"Group Key: Name = {group.Key.Name}, Age = {group.Key.Age}");

            foreach (var student in group)
            {
                Console.WriteLine($"Student Name: {student.Name}, Age: {student.Age}");
            }
        }
    }
}
Imports System
Imports System.Collections.Generic
Imports System.Linq

Public Module Program
	Public Sub Main()
		Dim studentList As New List(Of Student) From {
			New Student With {
				.Name = "Alice",
				.Age = 20
			},
			New Student With {
				.Name = "Alice",
				.Age = 21
			},
			New Student With {
				.Name = "Bob",
				.Age = 20
			},
			New Student With {
				.Name = "Charlie",
				.Age = 21
			}
		}

		' Group students by both Name and Age using an anonymous type as the key
		Dim groupedResult = studentList.GroupBy(Function(student) New With {
			Key student.Name,
			Key student.Age
		})

		For Each group In groupedResult
			Console.WriteLine($"Group Key: Name = {group.Key.Name}, Age = {group.Key.Age}")

			For Each student In group
				Console.WriteLine($"Student Name: {student.Name}, Age: {student.Age}")
			Next student
		Next group
	End Sub
End Module
$vbLabelText   $csharpLabel

在這個範例中,以匿名類型為關鍵,將學生依姓名和年齡分組。 結果是每個名稱和年齡的獨特組合都代表一個獨立的群組,展現出 GroupBy 在複雜群組情況下的彈性。

額外的 GroupBy 資訊

進階 GroupBy 使用方式

當您需要以多個關鍵值進行群組,或想要對群組資料執行其他操作(例如計數、篩選或排序)時,GroupBy 就會變得更加強大。 您可以透過將 GroupBy 與其他 LINQ 方法結合,或使用匿名類型以多個屬性進行群組,來達到此目的。

GroupBy 中的延遲執行

值得注意的是,GroupBy 採用延遲執行的方式,在以指定的關鍵迭代時處理項。 這表示在呼叫 GroupBy 方法時,不會立即執行群組操作。 相反地,執行會延遲到群組資料被遍歷之後,例如在 foreach 環路中。這種行為很有效率,因為它允許在資料最後被處理之前進行進一步的查詢最佳化和修改。

將 IronPDF 介紹給 C# 專案。

C# GroupBy (How It Works For Developers):圖 2 - IronPDF 網頁

IronPDF 是一個適用於 C# 的全面函式庫,可讓開發人員在 .NET 應用程式中建立、處理和轉換 PDF 文件。 這個功能強大的工具提供廣泛的功能,從從 HTML 產生 PDF 到編輯現有的 PDF 檔案等等。 IronPDF 可簡化將 PDF 功能整合至應用程式的過程,使其成為任何需要處理 PDF 的專案的寶貴資產。

IronPDF 的主要特點是其HTML 到 PDF 的轉換,確保版面設計和樣式得以保留。 它可從網頁內容產生 PDF,非常適合報告、發票和文件。 HTML 檔案、URL 和 HTML 字串可無縫轉換為 PDF。

using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 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");

        // 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");

        // 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();

        // 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");

        // 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");

        // 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()

		' 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")

		' 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")

		' 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
$vbLabelText   $csharpLabel

從群組資料產生 PDF 報表

讓我們延伸之前按年齡關鍵值將學生分組的範例。 將學生分組後,我們會使用 IronPDF 產生 PDF 報告,列出這些組別以及每組中的學生姓名。

using IronPdf;
using System;
using System.Collections.Generic;
using System.Linq;

public class Student
{
    public string Name { get; set; }
    public int Age { get; set; }
}

public class Program
{
    public static void Main()
    {
        // Initialize IronPDF license if applicable
        IronPdf.License.LicenseKey = "License";

        List<Student> studentList = new List<Student>
        {
            new Student { Name = "Alice", Age = 20 },
            new Student { Name = "Bob", Age = 20 },
            new Student { Name = "Charlie", Age = 21 },
            new Student { Name = "David", Age = 21 }
        };

        // Group students by their age
        var groupedResult = studentList.GroupBy(student => student.Age);

        // Create HTML content for the PDF report
        var htmlContent = "<h1>Student Report</h1>";

        foreach (var group in groupedResult)
        {
            htmlContent += $"<h2>Age Group: {group.Key}</h2><ul>";

            foreach (var student in group)
            {
                htmlContent += $"<li>{student.Name}</li>";
            }

            htmlContent += "</ul>";
        }

        // Initialize IronPDF renderer and generate PDF
        var renderer = new ChromePdfRenderer();
        var pdf = renderer.RenderHtmlAsPdf(htmlContent);

        // Specify path to save the PDF file
        var outputPath = "StudentReport.pdf";
        pdf.SaveAs(outputPath);

        Console.WriteLine($"PDF report generated at {outputPath}");
    }
}
using IronPdf;
using System;
using System.Collections.Generic;
using System.Linq;

public class Student
{
    public string Name { get; set; }
    public int Age { get; set; }
}

public class Program
{
    public static void Main()
    {
        // Initialize IronPDF license if applicable
        IronPdf.License.LicenseKey = "License";

        List<Student> studentList = new List<Student>
        {
            new Student { Name = "Alice", Age = 20 },
            new Student { Name = "Bob", Age = 20 },
            new Student { Name = "Charlie", Age = 21 },
            new Student { Name = "David", Age = 21 }
        };

        // Group students by their age
        var groupedResult = studentList.GroupBy(student => student.Age);

        // Create HTML content for the PDF report
        var htmlContent = "<h1>Student Report</h1>";

        foreach (var group in groupedResult)
        {
            htmlContent += $"<h2>Age Group: {group.Key}</h2><ul>";

            foreach (var student in group)
            {
                htmlContent += $"<li>{student.Name}</li>";
            }

            htmlContent += "</ul>";
        }

        // Initialize IronPDF renderer and generate PDF
        var renderer = new ChromePdfRenderer();
        var pdf = renderer.RenderHtmlAsPdf(htmlContent);

        // Specify path to save the PDF file
        var outputPath = "StudentReport.pdf";
        pdf.SaveAs(outputPath);

        Console.WriteLine($"PDF report generated at {outputPath}");
    }
}
Imports IronPdf
Imports System
Imports System.Collections.Generic
Imports System.Linq

Public Class Student
	Public Property Name() As String
	Public Property Age() As Integer
End Class

Public Class Program
	Public Shared Sub Main()
		' Initialize IronPDF license if applicable
		IronPdf.License.LicenseKey = "License"

		Dim studentList As New List(Of Student) From {
			New Student With {
				.Name = "Alice",
				.Age = 20
			},
			New Student With {
				.Name = "Bob",
				.Age = 20
			},
			New Student With {
				.Name = "Charlie",
				.Age = 21
			},
			New Student With {
				.Name = "David",
				.Age = 21
			}
		}

		' Group students by their age
		Dim groupedResult = studentList.GroupBy(Function(student) student.Age)

		' Create HTML content for the PDF report
		Dim htmlContent = "<h1>Student Report</h1>"

		For Each group In groupedResult
			htmlContent &= $"<h2>Age Group: {group.Key}</h2><ul>"

			For Each student In group
				htmlContent &= $"<li>{student.Name}</li>"
			Next student

			htmlContent &= "</ul>"
		Next group

		' Initialize IronPDF renderer and generate PDF
		Dim renderer = New ChromePdfRenderer()
		Dim pdf = renderer.RenderHtmlAsPdf(htmlContent)

		' Specify path to save the PDF file
		Dim outputPath = "StudentReport.pdf"
		pdf.SaveAs(outputPath)

		Console.WriteLine($"PDF report generated at {outputPath}")
	End Sub
End Class
$vbLabelText   $csharpLabel

在這個範例中,我們首先使用 GroupBy 方法將學生依年齡分組。 然後,我們會建構一個 HTML 字串(此方法會傳回此字串),將這組資料格式化為一份報告,其中包含每個年齡群組的標題,以及每個群組下的學生姓名清單。之後,我們使用 IronPDF 的 ChromePdfRenderer 類將這個 HTML 字串轉換成 PDF 文件。 所產生的 PDF 將儲存為檔案,提供一份格式整齊、按年齡分類的學生報告。

輸出

以下是 IronPDF 生成的輸出 PDF:

C# GroupBy (How It Works For Developers):圖 3 - 上一個程式碼範例輸出的 PDF

結論

C# GroupBy (How It Works For Developers):圖 4 - IronPDF 授權計劃

C# 中的 GroupBy 方法是一個多功能且功能強大的工具,用來根據指定的關鍵對資料進行分組。 無論您是偏好使用 lambda 表達式的方法語法,還是更偏好宣告式的查詢語法,GroupBy 都能讓您以易於管理和閱讀的方式組織複雜的資料結構。 透過掌握 GroupBy 和其他 LINQ 方法,您可以大幅提升在 C# 應用程式中處理和分析資料的能力。

IronPDF 提供免費試用,供希望在購買前瞭解其功能的人士使用。 對於那些準備將其整合到他們的專案中的人來說,許可價格從 $999 起,這使得它成為在 C# 應用程式中進行專業級 PDF 操作和生成的一項值得的投資。

常見問題解答

C# 中的 GroupBy 方法是什麼?

在 C# 中,GroupBy 方法是 LINQ 的一個功能,它根據指定的鍵將數據來源的元素組織成組,簡化數據分析和操作。

GroupBy 方法如何在 C# 中與方法語法一起工作?

使用帶有 Lambda 表達式的方法語法,GroupBy 方法根據指定的鍵來分組元素。例如,您可以按年齡分組學生列表,創建具有相似年齡的學生群組。

可以使用查詢語法與 GroupBy 方法嗎?

是的,可以使用查詢語法與 GroupBy 方法,提供一種更接近 SQL 且富有表達性的方式來執行分組操作,特別是針對複雜的數據轉換。

如何使用 GroupBy 根據多個鍵分組數據?

您可以使用匿名對象或元組來根據多個鍵對數據分組,從而可以根據屬性組合進行更詳細的數據分析。

在 GroupBy 的上下文中什麼是延遲執行?

延遲執行意味著 GroupBy 操作在被調用時不會立即執行。它會在遍歷分組數據時處理,允許查詢優化。

您如何使用 C# 從分組數據生成 PDF 報告?

您可以使用 IronPDF 將格式化分組數據的 HTML 字串轉換成 PDF 文件。這樣可以輕鬆地從使用 GroupBy 分組的數據中生成格式整潔的 PDF 報告。

C# 中的一些高級分組技術是什麼?

C# 中的高級分組技術涉及使用匿名對象或元組根據多個鍵或屬性進行數據分組,增強執行複雜數據分析的能力。

IronPDF 如何在 .NET 應用中支持專業級 PDF 管理?

IronPDF 為 C# 開發者提供了創建和操作 PDF 文件的工具,包括從 HTML 內容生成 PDF 報告。這有助於在 .NET 應用中有效地管理專業級 PDF。

如何在 C# 中將 HTML 轉換為 PDF?

您可以使用 IronPDF 的 RenderHtmlAsPdf 方法將 HTML 字符串轉換為 PDF。您還可以使用 RenderHtmlFileAsPdf 將 HTML 文件轉換為 PDF。

Jacob Mellor, Team Iron 首席技術官
首席技術官

Jacob Mellor是Iron Software的首席技術官,也是開創C# PDF技術的前瞻性工程師。作為Iron Software核心代碼庫的原始開發者,他自公司成立以來就塑造了公司的產品架構,並與CEO Cameron Rimington將公司轉型為服務NASA、Tesla以及全球政府機構的50多人公司。

Jacob擁有曼徹斯特大學土木工程一級榮譽學士學位(1998年–2001年)。他於1999年在倫敦開立首家軟體公司,並於2005年建立了他的第一個.NET組件,專注於解決Microsoft生態系統中的複雜問題。

他的旗艦作品IronPDF和Iron Suite .NET程式庫全球已獲得超過3000萬次NuGet安裝,他的基礎代碼不斷在全球各地驅動開發者工具。擁有25年以上的商業經驗和41年的編碼專業知識,Jacob仍然專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

鋼鐵支援團隊

我們每週 5 天,每天 24 小時在線上。
聊天
電子郵件
打電話給我