I have two three tables books, authors and groups.
books: bookId, name, authorId....
authors: authorId, firstName, LastName....
groups: groupID, name, 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.
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:
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() }
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.