c# - C# Linq 查找匹配条件的记录,如果找到该记录,则返回所有相关记录
问题描述
我的问题:我正在搜索特定日期发生的帐户交易。如果我找到了当天的交易,那么我需要收集该帐户的交易历史并将其捆绑在一起。我当前的解决方案需要 2 个 linq 语句才能正确恢复数据。但是我还有其他一些数据库调用,所以我正在尝试减轻负载
我当前的解决方案:首先,我使用 linq 语句收集当天发生的所有交易并仅返回帐号。然后我重新运行几乎相同的查询,但这次使用我需要的所有内容并使用 where 子句中第一个查询中的帐号。我还发现 linq 不喜欢在 where 子句中使用我的匿名类型,因此我在此期间将帐号转换为列表。
我的请求:谁能帮我找到一种更有效的方法来恢复我需要的数据?如果有人可以建议我对匿名问题进行更改,我将不胜感激。错误:无法创建“匿名类型”类型的常量值。此上下文仅支持原始类型或枚举类型。
我的代码:
public ICollection<ACCOUNT_TRANS> GetTransactionsByDate(DateTime date)
{
//Get account transactions that occur on this date
var results = this.ACCOUNT_TRANS
.Select(at => new { at.FK_ACCOUNT, at.COMPLETION_DATE })
.Where(at => at.COMPLETION_DATE.Value.Day == date.Day &&
at.COMPLETION_DATE.Value.Month == date.Month &&
at.COMPLETION_DATE.Value.Year == date.Year)
.ToList();
//Extract Account Number and removes the anonymous nature of the data
var accountNums = results.Select(r => r.FK_ACCOUNT).ToList();
//Return Transaction history for all changed changed
var results2 = this.ACCOUNT_TRANS
.Include(at => at.ACCOUNT_TABLE1)
.Include(at => at.ACCOUNT_TABLE2)
.Include(at => at.ACCOUNT_TABLE3)
.Include(at => at.ACCOUNT_TABLE4)
.Where(at => accountNums.All(r => r == at.FK_ACCOUNT))
.ToList();
return results2;
}
解决了
问题解决了,因为我的头因尝试了这么多事情而扭曲。这是代码应该是什么。Linq 想要的方式既好又简单:
public ICollection<ACCOUNT_TRANS> GetTransactionsByDate(DateTime date)
{
//Return Transaction history for all changed changed
var results = this.ACCOUNT_TRANS
.Include(at => at.ACCOUNT_TABLE1)
.Include(at => at.ACCOUNT_TABLE2)
.Include(at => at.ACCOUNT_TABLE3)
.Include(at => at.ACCOUNT_TABLE4)
.Where(at => at.COMPLETION_DATE.Value.Day == date.Day &&
at.COMPLETION_DATE.Value.Month == date.Month &&
at.COMPLETION_DATE.Value.Year == date.Year)
.ToList();
return results;
}
解决方案
试试这个查询,只是这个查询。
var results2 = this.ACCOUNT_TRANS
.Include(at => at.ACCOUNT_TABLE1)
.Include(at => at.ACCOUNT_TABLE2)
.Include(at => at.ACCOUNT_TABLE3)
.Include(at => at.ACCOUNT_TABLE4)
.Where(at => this.ACCOUNT_TRANS
.Where(a => at.COMPLETION_DATE.Value.Day == date.Day &&
a.COMPLETION_DATE.Value.Month == date.Month &&
a.COMPLETION_DATE.Value.Year == date.Year)
.Select(a => a.FK_ACCOUNT).Contains(at.FK_ACCOUNT))
.ToList();
推荐阅读
- node.js - Nodejs API - 使用 Passport JWT 策略与 jsonwebtoken 进行身份验证
- javascript - 使用悬停功能在随机位置生成 div,Jquery
- javascript - AWS AppSync Javascript 订阅引发 404 错误
- javascript - JS 日期 API:两个日期之间的差异(以小时为单位)——当前日期的奇怪行为
- php - 用于取消关注 instagram 取消关注者的 cURL 代码
- javascript - HTML 表格未使用 CSS 更新
- python - Python 2 is_integer 没有正确返回
- elastic-stack - ELK,文件节拍从消息中删除了一些文本
- python - 生产中的观察者设计模式如何表现?
- c# - SonarQube MSBuild 运行程序中的程序化覆盖排除