【问题标题】:Using the Except clause for two DataTable objects对两个 DataTable 对象使用 except 子句
【发布时间】:2014-05-28 01:36:50
【问题描述】:

我目前想从具有各种字段的 DataTable 对象中选择各种记录,但我想排除其 CustomerID 存在于另一个 DataTable 中的记录。或多或少类似于在 SQL 中使用“Except”或“NOT IN”子句。在 SQL 中是

SELECT * FROM Table1 WHERE CustomerID Not In (SELECT CustomerID FROM Table2)

我想在另一个 DataTable 中设置结果。

这就是我所拥有的:

var test = (from dt1 in lastMonthFunded.AsEnumerable() 
select new { CustomerId = dt1.Field<int>("CustomerId"), 
           LoanNumber =  dt1.Field<Int32>("LoanNumber") })
          .Except(from dt2 in lastYearFunded 
          select new {customerNum=dt2.Field<Int32>("LoanNumber")});

Visual Studio 显示以下消息:

错误 1 ​​实例参数:无法从“System.Data.EnumerableRowCollection”转换为“System.Linq.IQueryable”

错误 2 'System.Data.EnumerableRowCollection' 不包含 'Except' 的定义和最佳扩展方法重载 'System.Linq.Queryable.Except(System.Linq.IQueryable, System.Collections.Generic.IEnumerable) ' 有一些无效的参数

【问题讨论】:

  • 您的具体问题是什么?
  • 谢谢约翰!我错过了。我发布的查询对我不起作用。 Visual Studio 抛出以下消息:错误 1 ​​实例参数:无法从 'System.Data.EnumerableRowCollection' 转换为 'System.Linq.IQueryable' 和
  • 它还补充说:错误2'System.Data.EnumerableRowCollection'不包含'Except'的定义和最佳扩展方法重载'System.Linq.Queryable.Except(System.Linq.IQueryable, System.Collections.Generic.IEnumerable)' 有一些无效参数
  • 请将该信息添加到您的问题中,并显示出现问题的行。

标签: c# sql-server linq linq-to-objects


【解决方案1】:

只要你的对象依赖于基于 IQUeryable 或 IEnumerable 的类,你应该可以使用 Linq:

var test = from dt1 in lastMonthFunded
           where !(from d2 in LastYearFunded
                   select d2.LoanNumber).Contains(dt1.LoanNumber)
           select dt1;

使用上述 LINQ,您将能够获取 LastYearFunded 中不存在的所有 lastMonthFunded 记录。

【讨论】:

  • 请添加此代码的解释。另外,请说明您是如何提出该代码的。这将对这位读者和未来的读者有所帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-05
  • 1970-01-01
  • 1970-01-01
  • 2016-05-21
  • 2021-08-01
  • 1970-01-01
相关资源
最近更新 更多