如何返回LinQ GroupBy

时间:2015-01-07 10:42:28

标签: asp.net-mvc linq group-by

按类别返回列表产品组时出错:

  

错误1无法隐式转换类型'System.Linq.IQueryable>'到'System.Linq.IQueryable'。存在显式转换(您是否错过了演员?)

我的代码:

public IQueryable<GroupModel> GetAll()
    {
        List<Category> listCategories = new List<Category>
        {
            new Category {Id = 1, CateName = "SmartPhone", Description = "aaaaaa"},
            new Category {Id = 2, CateName = "Laptop", Description = "bbbb"},
            new Category {Id = 3, CateName = "Desktop", Description = "ccccc"},
        };

        List<Product> listProducts = new List<Product>
        {
            new Product {Id = 1, ProdName = "Lumia 720", CategoryId = 1, ColorId = 2},
            new Product {Id = 2, ProdName = "PC HP", CategoryId = 3, ColorId = 1},
            new Product {Id = 3, ProdName = "PC Dell", CategoryId = 3, ColorId = 1},
            new Product {Id = 4, ProdName = "Laptop Lenovo", CategoryId = 2, ColorId = 2},
            new Product {Id = 5, ProdName = "Lumia 920", CategoryId = 1, ColorId = 2},
            new Product {Id = 6, ProdName = "Laptop Dell", CategoryId = 2, ColorId = 3},
            new Product {Id = 7, ProdName = "Laptop HP", CategoryId = 2, ColorId = 3},
            new Product {Id = 7, ProdName = "Lumia 1020", CategoryId = 1, ColorId = 1}
        };

        List<Color> listColors = new List<Color>
        {
            new Color {ColorId = 1, ColorName = "Blue"},
            new Color {ColorId = 2, ColorName = "Yellow"},
            new Color {ColorId = 3, ColorName = "Red"}
        };

        var query = (from p in listProducts
                     join co in listColors on p.ColorId equals co.ColorId
                     join c in listCategories on p.CategoryId equals c.Id into e
                     from j in e.DefaultIfEmpty()

                     select new GroupModel
                     {
                         CategoryId = j.Id,
                         CategoryName = j.CateName,
                         ProductId = p.Id,
                         ProductName = p.ProdName,
                         ColorId = co.ColorId,
                         ColorName = co.ColorName

                     }).ToList().GroupBy(x => x.CategoryName);



        return query.AsQueryable();
    }

2 个答案:

答案 0 :(得分:1)

尝试关注最后一句话

return query.SelectMany(x=>x).AsQueryable();

答案 1 :(得分:1)

您的linq查询返回IGrouping<string,GroupViewModel>而不是IQueryable<GroupViewModel>。将您的方法签名更改为:

public IQueryable<IGrouping<string,GroupViewModel>> GetAll()
{
 var query = (from p in listProducts
             .......................
             .......................
 return query.AsQueryable<IGrouping<string,GroupViewModel>>();

}

DEMO FIDDDLE