我已设置以下方案,我需要返回尚未提交当天参赛作品的用户。
以下是正在使用的样本数据
var entries = new List<Entry> {
new Entry { UserId = "fce465f6-089d-4416-a631-7b8201c759d6", Name = "Bugs Bunny", Email = "bugs@bunny.com", CreatedDate = DateTime.Now.AddDays(-1) },
new Entry { UserId = "1b77f86a-4aad-4788-aa0c-791a7b734181", Name = "Daffy Duck", Email = "daffy@duck.com", CreatedDate = DateTime.Now.AddDays(-1) },
new Entry { UserId = "b293bc9d-7626-4c66-888b-e45daebf8322", Name = "Yosemite Sam", Email = "yosemite@sam.com", CreatedDate = DateTime.Now.AddDays(-1) }
new Entry { UserId = "ff8321fa-b241-456a-b618-826fdd75aaf2", Name = "Pepe Le Pew", Email = "pepe@lepew.com", CreatedDate = DateTime.Now.AddDays(-1) },
new Entry { UserId = "fce465f6-089d-4416-a631-7b8201c759d6", Name = "Bugs Bunny", Email = "bugs@bunny.com", CreatedDate = DateTime.Now.AddDays(0) },
new Entry { UserId = "1b77f86a-4aad-4788-aa0c-791a7b734181", Name = "Daffy Duck", Email = "daffy@duck.com", CreatedDate = DateTime.Now.AddDays(0) },
new Entry { UserId = "b293bc9d-7626-4c66-888b-e45daebf8322", Name = "Yosemite Sam", Email = "yosemite@sam.com", CreatedDate = DateTime.Now.AddDays(0) }
};
entries.ForEach(e => context.Entries.Add(e));
context.SaveChanges();
在这种情况下,我希望返回一条记录,因为当天没有 Pepe Le Pew 的条目。
我使用了以下代码段,但我很难理解 Where 语句。
var entries = db.Entries
.GroupBy(e => e.UserId)
.Select(g => g.OrderByDescending(e => e.CreatedDate)
.Where(e =>
DbFunctions.TruncateTime(e.CreatedDate) < currentDay.Date
&& DbFunctions.TruncateTime(e.CreatedDate) != currentDay.Date)
.FirstOrDefault())
.ToList();
有什么想法吗?
更新
@DavidG对以下解决方案的大量赞誉
var entries = db.Entries
.Where(e => DbFunctions.TruncateTime(e.CreatedDate) < currentDay.Date)
.Select(e => e.UserId)
.Except(db.Entries.Where(e => DbFunctions.TruncateTime(e.CreatedDate) == currentDay.Date).Select(e => e.UserId))
.ToList();
答案 0 :(得分:1)
您需要从所有唯一身份用户的列表开始,例如:
var allUsers = entries
.GroupBy(u => new { u.UserId })
.Select(u => new u.Key.UserId);
然后,您有一个查询来获取今天提交条目的所有用户:
var entriesToday = db.Entries
.Where(e => DbFunctions.TruncateTime(e.CreatedDate) == currentDay.Date)
.GroupBy(e => e.UserId)
.Select(g => g.Key);
现在使用Except
将它们组合成一个大查询:
var entries = db.Entries
.GroupBy(u => new { u.UserId })
.Select(u => u.Key.UserId)
.Except(db.Entries
.Where(e => DbFunctions.TruncateTime(e.CreatedDate) == currentDay.Date)
.GroupBy(e => e.UserId)
.Select(g => g.Key);
或者因为这将使用延迟执行,您可以使用前两个查询的结果来简化它:
var entries = allUsers.Except(entriesToday);