以下是一个按列对DataTable进行分组并转换为List
using System;
using System.Data;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
// 创建一个示例DataTable
DataTable dt = new DataTable();
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Age", typeof(int));
dt.Columns.Add("City", typeof(string));
dt.Rows.Add("John", 25, "New York");
dt.Rows.Add("Alice", 30, "London");
dt.Rows.Add("Bob", 35, "Paris");
dt.Rows.Add("Emily", 28, "Tokyo");
dt.Rows.Add("Mike", 32, "New York");
dt.Rows.Add("Tom", 29, "London");
// 按列进行分组并转换为List
List groupedTables = GroupByColumn(dt, "City");
// 输出每个分组的DataTable
foreach (DataTable group in groupedTables)
{
Console.WriteLine("Group: " + group.TableName);
foreach (DataRow row in group.Rows)
{
Console.WriteLine(row["Name"] + "\t" + row["Age"] + "\t" + row["City"]);
}
Console.WriteLine();
}
}
public static List GroupByColumn(DataTable dt, string columnName)
{
// 创建一个Dictionary用于保存分组后的DataTable
Dictionary
上述代码首先创建了一个示例的DataTable,并包含三列:Name、Age和City。然后使用GroupByColumn方法按照City列进行分组,将分组后的DataTable保存到一个Dictionary中。最后将Dictionary中的DataTable转换为List,并进行输出展示。