代码之家  ›  专栏  ›  技术社区  ›  Kamyar

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

  •  0
  • Kamyar  · 技术社区  · 14 年前

    我想定义一个从System.Data.DataTable派生的类。
    PopulateColumns 方法,您可以猜测该方法将填充数据表。 我试着用 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 回复  |  直到 14 年前
        1
  •  2
  •   SnickersAreMyFave    14 年前

    这比你想象的要简单得多:

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