在实际环境中测试
在生产中测试无水印。
随时随地为您服务。
在 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 表达式按年龄键值对学生进行分组。 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 字符串,该方法返回的 HTML 字符串将分组数据格式化为一份报告,报告中包含每个年龄组的标题和每个组下的学生姓名列表。然后使用 IronPDF 的 ChromePdfRenderer 类将 HTML 字符串转换为 PDF 文档。生成的 PDF 文件将保存到文件中,提供一份格式整洁的按年龄分组的学生报告。
下面是 IronPDF 生成的 PDF 输出:
C# 中的 GroupBy 方法是根据指定键对数据进行分组的通用而强大的工具。无论您是喜欢使用 lambda 表达式的方法语法,还是更喜欢声明式查询语法,GroupBy 都能让您以易于管理和阅读的方式组织复杂的数据结构。通过掌握 GroupBy 和其他 LINQ 方法,您可以大大提高在 C# 应用程序中处理和分析数据的能力。
IronPDF 提供了一个 免费试用 对于那些希望在购买前了解其功能的用户来说,"$LiteLicense "是一个不错的选择。对于那些准备将其集成到自己项目中的用户,许可证的起价为"$liteLicense",使其成为在 C# 应用程序中进行专业级 PDF 操作和生成的一项值得投资的项目。