using System;
using System.Data;
class Program
{
static void Main()
{
// 创建一个 DataTable 并添加一些数据
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Category", typeof(string));
dt.Rows.Add(1, "Product A", "Category 1");
dt.Rows.Add(2, "Product B", "Category 1");
dt.Rows.Add(3, "Product C", "Category 2");
dt.Rows.Add(4, "Product D", "Category 2");
dt.Rows.Add(5, "Product E", "Category 3");
// 使用 LINQ 对 DataTable 进行分组
var groupedData = from row in dt.AsEnumerable()
group row by row.Field<string>("Category") into g
select new
{
Category = g.Key,
Count = g.Count(),
Products = g.Select(r => r.Field<string>("Name"))
};
// 输出分组结果
foreach (var group in groupedData)
{
Console.WriteLine($"Category: {group.Category}, Count: {group.Count}");
Console.WriteLine("Products:");
foreach (var product in group.Products)
{
Console.WriteLine($"- {product}");
}
Console.WriteLine();
}
}
}
创建 DataTable:
DataTable,并添加了三列:ID、Name 和 Category。使用 LINQ 进行分组:
DataTable 中的数据进行分组。我们按 Category 列进行分组。Category 的值)、该分组中的行数以及每个分组中的产品名称列表。输出分组结果:
这个示例展示了如何使用 LINQ 对 DataTable 中的数据进行分组,并提取有用的信息。
上一篇:c# tcp client
下一篇:c# 二进制
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站