使用自定义类型填充数据表列

发布于 2024-09-30 08:16:25 字数 781 浏览 0 评论 0原文

我想定义一个派生自 System.Data.DataTable 的类。
这个类有一个 PopulateColumns 方法,您可以猜到它会填充 DataTable。 我希望此方法能够使用任意数量的自定义数据类型动态填充数据表列。 (请参阅下面的代码以进行说明) 我尝试使用 Dictionary,而不是一一传递所有参数:

public void Populate(Dictionary<string, Type> dic)
   {
       foreach (var item in dic)
           this.Columns.Add(item.Key, item.Value);
   }  

并调用它:

var testDt = new TestDataTable();
Dictionary<string, Type> dicCols = new Dictionary<string, Type>();
dicCols.Add("Index", System.Type.GetType("System.Int32"));
dicCols.Add("Title", System.Type.GetType("System.String"));
testDt.Populate(dicCols);  

这工作正常。但它不能接受具有相同内容的两列(因为列名称是字典中的键)。
我知道我不需要传递两个同名的列。但我只是好奇是否有更好的方法。

I'd like to define a class which is derived from System.Data.DataTable.
This class has a PopulateColumns method which as you can guess populate the DataTable.
I want this method to be able to dynamically populate the datatable columns with any number custom data types. (See my code below for clarification)
I tried using Dictionary<strin,Type>, instead of passing all the parameters one by one:

public void Populate(Dictionary<string, Type> dic)
   {
       foreach (var item in dic)
           this.Columns.Add(item.Key, item.Value);
   }  

And Call it:

var testDt = new TestDataTable();
Dictionary<string, Type> dicCols = new Dictionary<string, Type>();
dicCols.Add("Index", System.Type.GetType("System.Int32"));
dicCols.Add("Title", System.Type.GetType("System.String"));
testDt.Populate(dicCols);  

This works fine. but it cannot accept two columns with the same (Since column names are Keys in dictionary).
I know I don't need to pass two columns with the same name. But I'm just curious if there's a better way to do it.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

执着的年纪 2024-10-07 08:16:25

它比您想象的更简单:

    testDt.Columns.AddRange(new[] 
    {
        new DataColumn("Index", typeof(int)),
        new DataColumn("Title", typeof(string)),
    });

或者,您可以预先构建列表:(

    var columns = new[] 
    {
        new DataColumn("Index", typeof(int)),
        new DataColumn("Title", typeof(string)),
    };

    testDt.Columns.AddRange(columns);

数组、集合等都有一个 AddRange() 成员。)

It's more simple than you think:

    testDt.Columns.AddRange(new[] 
    {
        new DataColumn("Index", typeof(int)),
        new DataColumn("Title", typeof(string)),
    });

Or, you can build the list beforehand:

    var columns = new[] 
    {
        new DataColumn("Index", typeof(int)),
        new DataColumn("Title", typeof(string)),
    };

    testDt.Columns.AddRange(columns);

(Arrays, collections, etc. have an AddRange() member.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文