要将C# Dictionary转换为DataTable,可以使用以下代码示例:

using System;
using System.Data;

public class Program
{
    public static void Main()
    {
        // 创建一个Dictionary
        var dictionary = new Dictionary<string, string>();
        dictionary.Add("Name", "John");
        dictionary.Add("Age", "30");
        dictionary.Add("City", "New York");

        // 创建一个DataTable
        var dataTable = new DataTable();

        // 添加列
        dataTable.Columns.Add("Key", typeof(string));
        dataTable.Columns.Add("Value", typeof(string));

        // 添加行
        foreach (var item in dictionary)
        {
            var row = dataTable.NewRow();
            row["Key"] = item.Key;
            row["Value"] = item.Value;
            dataTable.Rows.Add(row);
        }

        // 打印DataTable
        foreach (DataRow row in dataTable.Rows)
        {
            Console.WriteLine(row["Key"] + ": " + row["Value"]);
        }
    }
}

在上面的示例中,我们首先创建了一个Dictionary并添加了一些键值对。然后,我们创建了一个DataTable,并添加了两个列,一个用于键,一个用于值。接下来,我们遍历Dictionary中的每个键值对,并将其添加到DataTable的行中。最后,我们打印出DataTable中的内容。

此代码将输出:

Name: John
Age: 30
City: New York
``
C# Dictionary转datatable

原文地址: https://www.cveoy.top/t/topic/ir1v 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录