【问题标题】:Comparing and Finding row value in DataTable C#在 DataTable C# 中比较和查找行值
【发布时间】:2020-12-05 07:18:31
【问题描述】:

我有一个用数据库表(两列)idclass 填充的 DataTable。我想将class 列的值与 string 进行比较,并找到对应的id 值。 classID 应该是 int 类型。

我的代码:

    int classID = from DataRow row in dtClassesDb.Rows where
                  row.ItemArray[1].ToString().Equals(table.TableName) 
                  select row.ItemArray[0];

【问题讨论】:

  • 如果您对高效查询感兴趣,可以考虑通过创建DataViewDataTable 中创建索引。看看this的问题。
  • 我已阅读链接问题。但就我而言,我该怎么做呢?

标签: c# linq foreach datatable


【解决方案1】:

通过将列class 的值与任何给定字符串进行比较,从DataTble 中找到Id

int classID = (int) dtClassesDb.AsEnumerable().
                FirstOrDefault(x => x.Field<string>(1) == "YourStringToCompare").
                ItemArray[0];

这里:

  • Field&lt;string&gt;(1) 正在使用列 class 索引,即 1
  • ItemArray[0] 正在使用列 Id 索引,即 0

这应该解决查询以获取Id

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-12
    • 1970-01-01
    • 2017-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多