在實際環境中測試
在生產環境中測試無浮水印。
在任何需要的地方都能運作。
在 C# 中, GroupBy 方法 是一個強大的工具,能根據指定的鍵將資料來源中的元素進行分組。這個方法是 LINQ 的一部分。 (語言集成查詢) 並且可以用於按單一屬性或多個屬性對項目進行分組,這使其在數據分析和操縱中非常寶貴。GroupBy 方法簡化了複雜的數據操作,允許基於特定標準進行高效的數據組織和檢索。我們將討論 Groupby 和 IronPDF 在這篇博客中的library。
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 表達式按學生的年齡鍵值分組。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操作和生成的一項有價值的投資。