【问题标题】:Populate Datatable columns with custom types使用自定义类型填充 Datatable 列
【发布时间】:2011-05-03 14:47:15
【问题描述】:

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

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

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

【问题讨论】:

    标签: c# .net-3.5 datatable populate


    【解决方案1】:

    比你想象的要简单:

        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() 成员。)

    【讨论】:

      猜你喜欢
      • 2010-10-28
      • 1970-01-01
      • 2019-03-31
      • 1970-01-01
      • 2014-07-27
      • 2016-03-24
      • 2015-11-04
      • 1970-01-01
      • 2019-06-28
      相关资源
      最近更新 更多