You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取DataTable中不匹配列值对应的行索引

获取DataTable中不匹配行的索引

你原本的代码用于提取dt1中ID_2列值不在dt2的ID列中的所有ID字符串:

Invalid_IDs = dt1.AsEnumerable() _
.Select(Function(row) row.Field(Of String)("ID_2")) _
.Except(dt2.AsEnumerable().Select(Function(row) row.Field(Of String)("ID")))

要改为获取这些不匹配行的行索引,可以通过以下方式实现:

优化后的代码

' 先把dt2的ID列值存入HashSet,提升后续查找效率
Dim dt2IdSet As New HashSet(Of String)(dt2.AsEnumerable().Select(Function(row) row.Field(Of String)("ID")))

' 获取dt1中ID_2不在dt2IdSet里的行的索引
Invalid_Indices = dt1.AsEnumerable() _
    .Select(Function(row, index) New With { .RowIndex = index, .IdValue = row.Field(Of String)("ID_2") }) _
    .Where(Function(item) Not dt2IdSet.Contains(item.IdValue)) _
    .Select(Function(item) item.RowIndex.ToString()) ' 若需要整数索引,改为 .Select(Function(item) item.RowIndex)

代码说明

  • 使用HashSet存储dt2的ID值:相比直接用Except,提前构建HashSet可以将查找操作的时间复杂度从O(n)降到O(1),数据量较大时效率提升明显。
  • 带索引的Select重载:通过Select(Function(row, index) ...)同时获取行数据和对应的行索引,保留索引信息不丢失。
  • 筛选并提取索引:通过Where过滤出不匹配的行,最后用Select提取出对应的索引,可根据需求选择返回整数类型或字符串类型的索引集合。

内容的提问来源于stack exchange,提问作者Fairy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 21:37:36