Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c# datatable group by

作者:傲世,小狂徒   发布日期:2025-11-19   浏览:48

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

解释说明

  1. 创建 DataTable:

    • 我们首先创建了一个 DataTable,并添加了三列:IDNameCategory
    • 然后向表中插入了几行数据。
  2. 使用 LINQ 进行分组:

    • 使用 LINQ 查询语法对 DataTable 中的数据进行分组。我们按 Category 列进行分组。
    • 每个分组包含一个键(即 Category 的值)、该分组中的行数以及每个分组中的产品名称列表。
  3. 输出分组结果:

    • 最后,我们遍历分组结果,并将每个分组的信息打印到控制台。

这个示例展示了如何使用 LINQ 对 DataTable 中的数据进行分组,并提取有用的信息。

上一篇:c# tcp client

下一篇:c# 二进制

大家都在看

c# 二进制

c# datatable group by

c# tcp client

c# type.gettype

c# sqlconnection

c# string.format 小数位数

.net和c#

c#获取系统时间

c#游戏开发

c#网络编程

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站