我有两个表(实体框架)。我想基于一个平均值来计算平均值,但是只计算一次记录。怎么做?

问题描述 投票:1回答:1

我有一张桌子,上面放着作者,一张桌子里放着书。它们连接在书的authorID中。我想根据类型来计算作者的平均年龄。看起来像这样:

  • 书籍:ID,书名,体裁,作者ID
  • 作者:作者ID,姓名,年龄

我想获得按类型分组的平均年龄。但是数据库中有同一作者的书籍。我只想在此查询中计算一次。我有这个,但是如果作者是同一个人的话,这会再次计数一次:

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,
                     };
c# sql .net database entity-framework
1个回答
0
投票

您快要在那里了,您只需要从选择的值中获​​取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)});
© www.soinside.com 2019 - 2024. All rights reserved.