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

时间:2010-11-01 19:40:51

标签: c# .net-3.5 datatable populate

我想定义一个派生自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);  

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

1 个答案:

答案 0 :(得分:2)

比你想象的更简单:

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

相关问题