如何按类别返回列表产品组 [英] How do I return a list Product group by Category

查看:78
本文介绍了如何按类别返回列表产品组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在分组数据时无法返回查询。请检查我的问题



I cannot return my query when I group data. Please check my issue

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

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

推荐答案

查询结果的类型为 IGrouping< string, GroupModel> 其中Key是字符串。您可以使用简单的foreach循环来提取所需的数据。

The result of your query is of type IGrouping<string, GroupModel> where the Key is the string. You can use simple foreach loops to extract the data you require.

List<GroupModel> groupModels= new List<GroupModel>();
         foreach (IGrouping<string, GroupModel> groupings in query)
         {
             foreach (GroupModel gm in groupings)
             {
                 groupModels.Add(gm);
             }
         }


这篇关于如何按类别返回列表产品组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆