gpt4 book ai didi

c# - 消除 LINQ to Entities 中的循环

转载 作者:行者123 更新时间:2023-11-30 21:59:21 25 4
gpt4 key购买 nike

我如何修改下面的查询以消除 foreach 循环并对数据库进行一次调用?

List<AuditLog> auditLogs = new List<AuditLog>();

foreach (TableRecordGuidPair pair in allTablesRecords)
{
var auditLogsFromDatabase = databaseContext.AuditLog.OrderBy(x => x.EventDateUtc)
.Where
(x => x.TableName == pair.TableName &&
x.RecordId == pair.RecordID)
.Select(auditLog => new AuditLog
{
AuditLogId = auditLog.AuditLogId,
}).ToList();
auditLogs.AddRange(auditLogsFromDatabase);
}

return auditLogs;

最佳答案

您可以像这样使用 SelectMany 选择所有列表:

return allTablesRecords
.SelectMany(pair =>
databaseContext.AuditLog.OrderBy(x => x.EventDateUtc)
.Where(x => x.TableName == pair.TableName && x.RecordId == pair.RecordID)
.Select(auditLog => new AuditLog
{
AuditLogId = auditLog.AuditLogId,
})
)
.ToList();

或者,你可以做一个连接

return (from allTableRecords pair
join databaseContext.AuditLog auditLog
on new { pair.TableName, pair.RecordId } equals new { auditLog.TableName, auditLog.RecordId }
select new {
AutitLogId = auditLog.AuditLogId
})
.ToList();

关于c# - 消除 LINQ to Entities 中的循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29307460/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com