我有一个C#代码,如下所示:
foreach (var entry in this.ChangeTracker.Entries()
.Where(e => e.Entity is IAuditableTable &&
e.State == EntityState.Added))
{
IAuditableTable e = (IAuditableTable)entry.Entity;
e.ModifiedDate = DateTime.Now;
}
这似乎就像foreach和LINQ的结合。 sometone告诉我,我可以删除foreach并将其合并为一个LINQ语句
答案 0 :(得分:34)
我建议不要这样做。保持一切尽可能可读:
var auditableTables = this.ChangeTracker.Entries()
.Where(e => e.State == EntityState.Added)
.Select(e => e.Entity)
.OfType<IAuditableTable>();
foreach (var table in auditableTables)
{
table.ModifiedDate = DateTime.Now;
}
我对编码的经验法则 - 如果你不能像句子那样阅读,那就需要修复。
答案 1 :(得分:7)
你能做的最好的事情是
foreach (var entry in from x in this.ChangeTracker.Entries()
where x.Entity is IAuditableTable &&
x.State == EntityState.Added
select (IAuditableTable)x.Entity)
{
entry.ModifiedDate = DateTime.Now;
}
没有更新的查询语法。
答案 2 :(得分:4)
你走了:
this.ChangeTracker.Entries()
.Where(e => e.Entity is IAuditableTable && e.State == EntityState.Added)
.ToList()
.ForEach(entry => {
IAuditableTable e = (IAuditableTable) entry.Entity;
e.ModifiedDate = DateTime.Now;
});
答案 3 :(得分:3)
这应该这样做。
this.ChangeTracker.Entries()
.Where(e => e.Entity is IAuditableTable &&
e.State == EntityState.Added)
.ToList().ForEach(entry => {
IAuditableTable e = (IAuditableTable)entry.Entity;
e.ModifiedDate = DateTime.Now;
});