我如何 return LinQ GroupBy

How do I return a LinQ GroupBy

当我 return 按类别列出产品组时出现错误 :

Error 1 Cannot implicitly convert type 'System.Linq.IQueryable>' to 'System.Linq.IQueryable'. An explicit conversion exists (are you missing a cast?)

我的代码:

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();
    }

尝试按照最后一条语句进行操作

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

您的 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