【问题标题】:I have two tables (Entity Framework). I want to count an average based on one another, but only count one record once. How to do it?我有两个表(实体框架)。我想根据彼此计算平均值,但只计算一次记录。怎么做?
【发布时间】:2026-02-03 23:30:02
【问题描述】:

我有一张有作者的桌子,还有一张有书籍的桌子。它们在本书的authorID 中连接。我想根据流派计算作者的平均年龄。它看起来像这样:

  • 书籍:ID、书名、流派、作者 ID
  • 作者: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,
                     };

【问题讨论】:

  • 您首先查询给每个属性一个名称。发件人:books.booktype,收件人:bookType = books.booktype,

标签: c# sql .net database entity-framework


【解决方案1】:

您就快到了,您只需从您的选择中获取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)});

【讨论】: