[英]LINQ get rows from a table that don't exist in another table when using group by?
I have two three tables books, authors and groups. 我有两本三桌书籍,分别是作者和团体。
books: bookId, name, authorId.... 书籍:bookId,名称,authorId...。
authors: authorId, firstName, LastName.... 作者:authorId,firstName,LastName ....
groups: groupID, name, authorId... 组:groupID,名称,authorId ...
i need to select all authorIds
that doesn't belong to any groups and doesn't have less than 3 books published between two dates. 我需要选择不属于任何组并且在两个日期之间出版的书籍不少于3本书的所有
authorIds
。
List<int> authorId= new List<int>(db.Books.GroupBy(x => x.authorId)
.Where(x => x.Any(y => y.datePublished <= now && y.datePublished >= date) && x.Count() > 2)
.Select(x => x.FirstOrDefault().authorId)).Distinct().ToList();
Well, assuming that you're using Entity Framework and you have the proper navigation properties in your model, you can do something like this: 好吧,假设您使用的是Entity Framework,并且模型中具有适当的导航属性 ,则可以执行以下操作:
var authorIds= db.Authors
.Where(a=>a.Books.Count(y => y.datePublished <= now && y.datePublished >= date)>2 && !a.Groups.Any())
.ToList();
Another solution that came to my mind now but I'm not sure if it works is using two group joins : 现在我想到了另一个解决方案,但是我不确定是否可以使用两个组联接 :
var authorId=(from a in db.Authors
join b in db.Books on a.authorId equals b.authorId into g1
join g in db.Groups on a.authorId equals g.authorId into g2
where g1.Count(y => y.datePublished <= now && y.datePublished >= date)>0 && !g2.Any()
select a.authorId).ToList();
But I definitely prefer my first solution, it's more readable and easy too. 但是我绝对更喜欢我的第一个解决方案,它也更易读和易读。
I guess this would work: 我想这会工作:
List<int> authorId = (List<int>)db.Books
.Where(x => x.datePublished >= InitialDate)
.Where(x => x.datePublished <= FinalDate)
.GroupBy(x => x.authorId)
.Select(g => new { authorId = g.Key, count = g.Count() })
.Where(g => g.Count >= 3)
.Select(g.authorId);
I make every single step so you can see it better, fell free to optimized as needed. 我迈出了每一步,以便您可以更好地看到它,并根据需要随意进行优化。 The key thing here is the
new { authorId = g.Key, count = g.Count() }
. 这里的关键是
new { authorId = g.Key, count = g.Count() }
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.