Linq使用连接和分组

时间:2017-12-03 13:05:23

标签: c# asp.net linq

我试图做一些非常简单的事情。 我在数据库中有两个表,我想使用linq查询。 书籍表和GenreTypes表。此查询的结果将转到我的网络Api。

以下是代码段:

public List<BooksChart> GetBooksChart()
{
    var results = from b in _dbcontext.Books
                  join g in _dbcontext.GenreTypes
                  on b.GenreTypeId equals g.Id
                  group g by g.Name into n
                  select (z => new BooksChart
                  {
                      category_name = n.Key,
                      value = n.Count()
                  }).ToList();

    return results;
}

public class BooksChart
{
    public string category_name;
    public int value;
}

分组的结果&#34; n&#34;我想将它们存储在BooksChart类中以构建Api。

此代码未编译。

以前,我只查询一个书籍表,我将其分为书籍和流派类型。

我以前查询图书的工作代码是:

var results = _dbcontext
    .Books
    .GroupBy(x => x.GenreType)
    .Select(z => new BooksPieChart
    {
        category_name = z.Key,
        value = z.Count()
        }).ToList();

        return results;

修改

我想在SQL中实现的目标如下:

select count(*), g.Name
from books b, GenreTypes g
where b.GenreTypeId = g.Id
group by g.Name;

2 个答案:

答案 0 :(得分:2)

您正在混合查询和方法的两个语法选项。对于查询语法,您需要执行投影(select),如下所示:

return (from b in _dbcontext.Books
        join g in _dbcontext.GenreTypes on b.GenreTypeId equals g.Id
        group g by g.Name into n
        select new BooksChart {
            category_name = n.Key,
            value = n.Count()
        }).ToList();

(z =>....)的格式是传递给Select方法的labmda的声明。

网站说明:

答案 1 :(得分:2)

括号必须包围整个查询,如下所示:

var results = (from b in _dbcontext.Books
               join g in _dbcontext.GenreTypes
               on b.GenreTypeId equals g.Id
               group g by g.Name into n
               select new BooksChart
               {
                   category_name = n.Key,
                   value = n.Count()
               }).ToList();

编译错误是由(z =>引起的,根本不需要。

相关问题