如何通过 LinQ 在列表视图中按类别对产品进行分组?
How to group product by category on list view by LinQ?
我是新手asp.net mvc !
我有一个列表视图来显示产品:
Id CateId CateName
1 2 Cate-B
|__ Product-B
2 1 Cate-A
|__ Product-A
3 1 Cate-A
|__ Product-C
但现在我想按类别显示列表视图组产品,如下所示。我该怎么做?
Id CateId CateName
1 2 Cate-B
|__ Product-B
2 1 Cate-A
|__ Product-B
|__ Product-C
这是我的代码:
public IQueryable<MyGroup> GetAllProduct()
{
var query = (from c in _categoryRepository.Table()
join p in _productRepository.Table() on c.Id equals p.CateId
select new MyGroup
{
Categories= c,
Products = p
}).ToList();
return query.AsQueryable();
}
使用 GroupBy 方法按类别 ID 分组。
例如。 Viewmodel.GroupBy(r => r.cateid)
见here
如果我没有正确理解你的问题,这就是你需要的:-
var query = _categoryRepository.Table()
.GroupBy(x => new { x.Id, x.CateId, x.CateName })
.Select(x => new
{
x.Key.Id,
x.Key.CateId,
x.Key.CateName,
ProductsNames = _productRepository.Table()
.Where(p => p.CategoryId == x.Key.CateId)
.Select(p => p.ProductName).ToList()
}).ToList();
这里是我使用 LINQ-To-Objects 的地方的 Demo。
我是新手asp.net mvc !
我有一个列表视图来显示产品:
Id CateId CateName
1 2 Cate-B
|__ Product-B
2 1 Cate-A
|__ Product-A
3 1 Cate-A
|__ Product-C
但现在我想按类别显示列表视图组产品,如下所示。我该怎么做?
Id CateId CateName
1 2 Cate-B
|__ Product-B
2 1 Cate-A
|__ Product-B
|__ Product-C
这是我的代码:
public IQueryable<MyGroup> GetAllProduct()
{
var query = (from c in _categoryRepository.Table()
join p in _productRepository.Table() on c.Id equals p.CateId
select new MyGroup
{
Categories= c,
Products = p
}).ToList();
return query.AsQueryable();
}
使用 GroupBy 方法按类别 ID 分组。
例如。 Viewmodel.GroupBy(r => r.cateid)
见here
如果我没有正确理解你的问题,这就是你需要的:-
var query = _categoryRepository.Table()
.GroupBy(x => new { x.Id, x.CateId, x.CateName })
.Select(x => new
{
x.Key.Id,
x.Key.CateId,
x.Key.CateName,
ProductsNames = _productRepository.Table()
.Where(p => p.CategoryId == x.Key.CateId)
.Select(p => p.ProductName).ToList()
}).ToList();
这里是我使用 LINQ-To-Objects 的地方的 Demo。