一、代码
using System;
using System.Collections.Generic;
using System.Data;
class Program
{
static void Main()
{
// 示例:构建一个 DataTable
DataTable res = new DataTable();
res.Columns.Add("Id", typeof(int));
res.Columns.Add("Name", typeof(string));
res.Columns.Add("Age", typeof(int));
res.Rows.Add(1, "John", 30);
res.Rows.Add(2, "Alice", 25);
res.Rows.Add(3, "Bob", 35);
// 获取相关数据:
var list = DtToDictionaryList(res); // 获取包含元组的列表
// 输出每行数据
foreach (var tuple in list)
{
// 输出字段名称、字段类型和字段内容
Console.WriteLine($"字段名称: {tuple.FieldName}, 字段类型: {tuple.FieldType}, 字段内容: {tuple.FieldValue}");
}
}
// 返回每个列名、列类型和列值的元组列表
public static List<(string FieldName, string FieldType, string FieldValue)> DtToDictionaryList(DataTable res)
{
var list = new List<(string FieldName, string FieldType, string FieldValue)>();
// 遍历每行数据
foreach (DataRow row in res.Rows)
{
// 遍历每列,获取字段名称、字段类型和字段值
foreach (DataColumn column in res.Columns)
{
var fieldName = column.ColumnName;
var fieldType = column.DataType.ToString();
var fieldValue = row[column].ToString();
// 添加元组到列表
list.Add((fieldName, fieldType, fieldValue));
}
}
return list;
}
}
二、输出效果
字段名称: Id, 字段类型: System.Int32, 字段内容: 1
字段名称: Name, 字段类型: System.String, 字段内容: John
字段名称: Age, 字段类型: System.Int32, 字段内容: 30
字段名称: Id, 字段类型: System.Int32, 字段内容: 2
字段名称: Name, 字段类型: System.String, 字段内容: Alice
字段名称: Age, 字段类型: System.Int32, 字段内容: 25
字段名称: Id, 字段类型: System.Int32, 字段内容: 3
字段名称: Name, 字段类型: System.String, 字段内容: Bob
字段名称: Age, 字段类型: System.Int32, 字段内容: 35