c# - 根据多个字段从两个表中选择不同的行
问题描述
我需要从一个表中选择另一个表中不存在的行。但是,我无法加入,ID
因为这些表来自不同的数据库。
我对每个数据库都有一个上下文,并使用以下 C# 代码来获取数据:
var forecastRows = targetContext.Forecasts.ToList();
var actualRows = sourceContext.Actual.ToList()
.Select(actual => new
{
TargetMonth = DateTimeExtensions.GetMonthCode(actual.Date.Year, actual.Date.Month),
CustomerCode = actual.CustomerGroupNo,
actual.Brand
});
然后我定义变量以从表中获取行Forecasts
,这些行在表中不存在Actual
:
var orphanActualRows = forecastRows.Where(row =>
!actualRows.Any(f => f.Brand == row.Brand.Code
&& f.CustomerCode == row.Customer.Code
&& f.TargetMonth == row.TargetMonth));
但它不能正常工作。它返回表的总数Forecasts
。但它不准确,因为行数要少得多......
解决方案
我认为这个加入可以帮助你。
var orpahanActualRows = targetContext.Forecast.Join(
sourceContext.Actual,
forecastRows => new { forecastRows.Brand, forecastRows.CustomerCode, forecastRows.TargetMonth },
actualRows => new { actualRows.Brand, actualRows.CustomerGroupNo, actualRows.Date.Year, actualRows.Date.Month},
(forecastRows, actualRows) => new { f = forecastRows, rows=actualRows })
.Where(d => d.rows.Brand.Code != d.f.Brand
&& d.rows.CustomerCode != d.f.CustomerCode
&& rows.TargetMonth != DateTimeExtensions.GetMonthCode(rows.Date.Year, rows.Date.Month))
.Select(d => d.f)
.ToList();
推荐阅读
- typescript - Flickity 渲染重复的幻灯片,直到 Inspector 关闭或打开
- c++ - 为什么 std::all_of() 的编码版本与对 std::all_of() 的调用不同?
- javascript - auth0 loginWithRedirect() 不同提供者的不同范围
- python - Python Selenium 等待不起作用/Java Selenium 问题
- r - R:函数返回未使用的参数
- loss-function - 我可以根据人口的子集为 GBM(或任何 ML 算法)指定损失函数吗?
- c# - Visual Studio 未找到任何引用或包
- windows - 无法在 Windows Server 上使用 Powershell 挂载 AzureFileShare
- android - 无法从 Kotlin 类中的 Java 类调用公共函数
- react-native - REACT NATIVE 回购之前购买的订单