【问题标题】:How to update a particular column in datatable?如何更新数据表中的特定列?
【发布时间】:2020-02-12 08:24:40
【问题描述】:

我有一个类似这样的数据表。

ColA      ColB       ColC
100       text10     text25
100       text15     
100                  text26
100                  text25
100       text14     text22

我想通过仅为数据表中的非空值添加前导和尾随字符来更改 ColB 和 ColC 中的值。

ColA      ColB       ColC
100       -text10-   -text25-
100       -text15-     
100                  -text26-
100                  -text25-
100       -text14-   -text22-

编辑:我可以通过遍历数据行并更新它来做到这一点。但我正在寻找更简单的选择。有没有办法使用 LINQ 来实现这一点?

【问题讨论】:

  • 你试过了吗?
  • 我是通过循环遍历所有数据行并更新它来完成的。但我正在寻找更简单的选择..
  • 不使用 LINQ,但原始 SQL 可以在单个操作中完成
  • 谢谢!您能否指出一个关于如何在数据表上实现原始 sql 更新的示例/文档。

标签: c# vb.net datatable


【解决方案1】:
Private dt As New DataTable

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    dt.Columns.Add("ColumnA", GetType(Integer))
    dt.Columns.Add("ColumnB", GetType(String))
    dt.Columns.Add("ColumnC", GetType(String))
    dt.Rows.Add(100, "text10", "text25")
    dt.Rows.Add(100, "text15")
    dt.Rows.Add(100, "", "text26")
    dt.Rows.Add(100, "", "text25")
    dt.Rows.Add(100, "text14", "text22")
End Sub

Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
    For Each row As DataRow In dt.Rows
        Dim colB As String = row(1).ToString
        Dim colC As String = row(2).ToString
        If Not String.IsNullOrEmpty(colB) Then
            row(1) = $"-{colB}-"
        End If
        If Not String.IsNullOrEmpty(colC) Then
            row(2) = $"-{colC}-"
        End If
    Next
    DataGridView1.DataSource = dt
End Sub

我分别测试了 ColumnB 和 ColumnC,并使用插值字符串更新了 DataGable 中的数据。

【讨论】:

  • OP想在LINQ实现它
【解决方案2】:

LINQ 的实现方式如下:

假设您的 DbContext 在 EF 中的名称是“testEntities”,表名称是 multicols。你可以试试:

using (var db = new testEntities())
{
    (from m in db.multicols
          where m.ColB != null || m.ColC != null //Dont pull if both columns are null
          select m).ToList().ForEach( m =>
          {
              m.ColB = String.IsNullOrEmpty(m.ColB) ? m.ColB : $"-{m.ColB}-";
              m.ColC = String.IsNullOrEmpty(m.ColC) ? m.ColC : $"-{m.ColC}-";
           });

    db.SaveChanges();
}

【讨论】:

  • 这段代码会更新这一行吗? 100 -text26-It seems your Where... AndAlso... 检查两列是否为空。
  • @mary 好点。实际上我想排除两列是否都是NULL
猜你喜欢
  • 1970-01-01
  • 2010-12-06
  • 2013-02-21
  • 1970-01-01
  • 1970-01-01
  • 2012-08-15
  • 2014-08-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多