我有一张桌子,上面放着作者,一张桌子里放着书。它们连接在书的authorID
中。我想根据类型来计算作者的平均年龄。看起来像这样:
我想获得按类型分组的平均年龄。但是数据库中有同一作者的书籍。我只想在此查询中计算一次。我有这个,但是如果作者是同一个人的话,这会再次计数一次:
var query = from books in this.bookRepository.ReadAll()
join authors in this.authorRepository.ReadAll() on books.writerId equals authors.authorId
select new
{
books.booktype,
authors.age,
authors.authorId,
};
var result = from g in query
group g by g.booktype into groupedTypes
select new AverageOfWritersAgeInGenreModel
{
Genre = groupedTypes.Key,
Age = groupedTypes.Average(x => x.age).Value,
};
您快要在那里了,您只需要从选择的值中获取Distinct
值:
select new
{
books.booktype,
authors.age,
authors.authorId,
};
我已经将代码重写为LINQ扩展:
var authors = new List<Author>(); // for simplicity
var books = new List<Book>(); // for simplicity
var result = authors
.Join(books, a => a.AuthorId, b => b.AuthorId,
(author, book) => new {author.AuthorId, author.Age, book.Genre})
.Distinct() // Ged rid of duplicated authors for the same book genre
.GroupBy(r => r.Genre)
.Select(g => new {Genre = g.Key, Age = g.Average(x => x.Age)});