【问题标题】:Append a column to an existing Datatable with dynamically bound values将列附加到具有动态绑定值的现有数据表
【发布时间】:2015-03-23 14:25:58
【问题描述】:

我在 Vb 中有以下数据表

   Id            Price
  -----          -------
   1231           100
   1232           150
   1235           150

我想在名为flag 的数据表中添加第三列,其最后一位的值为Id

如下:

    Id               Price         Flag
   -----            ------       ----------
    1231             100             1
    1232             150             2
    1235             150             5

如何使用动态绑定值将列附加到现有数据表?

有没有一种方法可以在不使用 For 循环的情况下做到这一点?

任何帮助将不胜感激

【问题讨论】:

    标签: c# vb.net datatable


    【解决方案1】:

    您首先需要添加一个DataColumn

    table.Columns.Add("Flag", typeof(int));
    

    现在您只需要相应地添加值:

    foreach(DataRow row in table.Rows)
    {
        int ID = row.Field<int>("ID");
        string lastDigit = ID.ToString().Last().ToString();
        row.SetField("Flag", int.Parse(lastDigit));
    }
    

    避免循环的唯一方法是首先用这些值填充它,例如,如果它是从数据库填充的。因此,即使存在 DataColumn.Expression 方法(这里不是这种情况)也会导致框架中的循环。

    【讨论】:

    • 没有for循环有没有办法做到这一点?
    • @HelpASisterOut:不,没有。即使“有”一种方法(比如DataColumn.Expression),框架也会隐式使用循环。
    【解决方案2】:

    有没有一种方法可以在不使用 For 循环的情况下做到这一点?

    是的,添加一个带有以下expression 的计算列:

    [id] % 10
    

    示例(vb.net):

    Using table As New DataTable()
    
        table.Columns.Add("Id", GetType(Integer))
        table.Columns.Add("Price", GetType(Decimal))
    
        table.Rows.Add(1231I, 100D)
        table.Rows.Add(1232I, 150D)
        table.Rows.Add(1235I, 150D)
    
        'Add a new computed column:                    expr
        table.Columns.Add("Flag", GetType(Integer), "[id] % 10")
    
        For Each row As DataRow In table.Rows
            Debug.WriteLine("{0}    {1}    {2}", row.ItemArray)
        Next
    
    End Using
    

    示例(C#):

    using (DataTable table = new DataTable())
    {
    
        table.Columns.Add("Id", typeof(int));
        table.Columns.Add("Price", typeof(decimal));
    
        table.Rows.Add(1231, 100M);
        table.Rows.Add(1232, 150M);
        table.Rows.Add(1235, 150M);
    
        //Add a new computed column:              expr
        table.Columns.Add("Flag", typeof(int), "[id] % 10");
    
        foreach (DataRow row in table.Rows)
        {
            Debug.WriteLine("{0}    {1}    {2}", row.ItemArray);
        }
    
    }
    

    输出:

    1231 100 1 1232 150 2 1235 150 5

    【讨论】:

    • 调试我添加计算列的部分需要很长时间而没有响应。你为什么这么认为?
    • 多少行?我用包含 100 万行的表进行了测试,耗时约 2 秒。
    猜你喜欢
    • 2016-09-27
    • 2012-05-23
    • 1970-01-01
    • 1970-01-01
    • 2011-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-12
    相关资源
    最近更新 更多