在實際環境中測試
在生產環境中測試無浮水印。
在任何需要的地方都能運作。
在 C# 中,GroupBy 方法是一個強大的工具,可根據指定的鍵將數據來源中的元素組織成組。 此方法是 LINQ 的一部分(語言集成查詢)並且可以用來按照單一屬性或多個屬性對項目進行分組,使其在資料分析和操作中變得非常寶貴。 GroupBy 方法簡化了複雜的數據操作,允許根據特定標準有效地組織和檢索數據。 我們將討論 GroupBy 和IronPDF 程式庫在此博客中。
GroupBy 方法的本質在於能夠根據指定的鍵將給定集合的元素分類成組。 此關鍵屬性決定了項目如何分組。 例如,您可以依據年齡鍵值將學生列表分組,從而創建年齡相同的學生群組。 每個群組由一個鍵值和共享該鍵的一組項目表示。 鍵屬性可以是任何對象,例如字串、數字,甚至是匿名對象,這提供了如何分組數據的靈活性。
在 C# 中,有兩種方式應用 GroupBy 方法:方法語法和查詢語法。 方法語法使用 lambda 表達式來定義分組鍵,這是一種直接應用 GroupBy 操作的方法。
考慮以下使用方法語法按年齡將學生列表分組的示例:
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 }
};
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}");
}
}
}
}
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 }
};
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}");
}
}
}
}
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
}
}
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
LINQ 的 GroupBy 方法使用 lambda 表達式將學生按其 Age 鍵值分組。 group.Key 代表年齡組,而內部的 foreach 迴圈則迭代組內的每個學生,打印他們的名字。
查詢語法提供了一種更加表達性的分組操作方式,類似於 SQL 查詢。 這在處理複雜數據轉換和多重分組標準時特別有用。 以下是使用查詢語法實現與上一個範例類似功能的方法:
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 }
};
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}");
}
}
}
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 }
};
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}");
}
}
}
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
}
}
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
在此片段中,查詢語法按年齡對學生進行分組,類似於方法語法,但語法不同,有些人會覺得這樣更易讀。
更高級的 GroupBy 方法用法涉及通過多個鍵或屬性對數據進行分組。 此技術允許基於多個值進行更詳細的數據分析和分類。 通過使用匿名物件或元組,您可以根據多個屬性的組合來分組項目,為您的應用程式提供更豐富的資料結構。
考慮一個情境,需要將學生不僅按年齡主值來分組,還要按姓名分組,以識別列表中姓名和年齡主值相同的學生。這可以通過按包含姓名和年齡的匿名類型進行分組來完成。
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 }
};
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}");
}
}
}
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 }
};
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}");
}
}
}
Public Shared 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
}
}
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
在這個例子中,使用匿名型別作為鍵,將學生按姓名和年齡分組。 這將導致形成一個個組,每個獨特的姓名和年齡組合都作為一個單獨的組來表示,展示了 GroupBy 對於複雜分組情境的靈活性。
當您需要按多個鍵值進行分組,或希望對分組數據執行其他操作(例如計數、篩選或排序)時,GroupBy 變得更加強大。 您可以通過將 GroupBy 與其他 LINQ 方法結合使用,或使用匿名類型按多個屬性進行分組來實現此目的。
請注意,GroupBy 使用延遲執行,在透過給定的鍵進行迭代時才會處理項目。 這意味著當呼叫 GroupBy 方法時,分組操作不會立即執行。 相反,執行會延遲到分組數據被遍歷時,例如在 foreach 循環中。這種行為很高效,因為它允許在最終處理數據之前進一步進行查詢優化和修改。
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();
// 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
讓我們擴展之前將學生按年齡鍵值分組的例子。 在分組學生後,我們將使用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()
{
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 }
};
var groupedResult = studentList.GroupBy(student => student.Age);
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>";
}
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf(htmlContent);
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()
{
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 }
};
var groupedResult = studentList.GroupBy(student => student.Age);
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>";
}
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf(htmlContent);
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()
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
}
}
Dim groupedResult = studentList.GroupBy(Function(student) student.Age)
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
Dim renderer = New ChromePdfRenderer()
Dim pdf = renderer.RenderHtmlAsPdf(htmlContent)
Dim outputPath = "StudentReport.pdf"
pdf.SaveAs(outputPath)
Console.WriteLine($"PDF report generated at {outputPath}")
End Sub
End Class
在此示例中,我們首先使用 GroupBy 方法按年齡對學生進行分組。 接著,我們構建一個HTML字串,這個方法會回傳該字串,將這些分組資料格式化成報告,每個年齡組都有標題,並在每個組別下列出學生名稱。IronPDF的ChromePdfRenderer類別隨後被用來將這個HTML字串轉換成PDF文件。 生成的 PDF 被保存到文件中,提供了按年齡分組的學生整齊格式報告。
以下是由 IronPDF 生成的輸出 PDF:
在 C# 中,GroupBy 方法是一個多功能且強大的工具,用於根據指定的鍵對數據進行分組。 無論您偏好使用帶有 lambda 表達式的方法語法,還是更具聲明性的查詢語法,GroupBy 都能使您以可管理且易讀的方式組織複雜的數據結構。 通過掌握 GroupBy 和其他 LINQ 方法,您可以顯著提升在 C# 應用程式中操作和分析數據的能力。
IronPDF 提供一個免費試用對於那些想在購買前探索其功能的人來說。 對於準備將其整合到專案中的人員,授權價格從 $749 起,使其成為在 C# 應用程式中進行專業級 PDF 操作和生成的一項值得投資的選擇。