我想知道如何使用 LINQ 对表中的行进行分组。下面的代码成功地用数据库中的数据加载了我的网格,所以我的要求是选择它们并将它们分组为商店和项目。
[HttpGet]
public object Get()
{
return new { Items = _context.farmtable
.Select(x => new {x.Id, x.Item, x.Store, x.Location })
.ToList(), Count = _context.farmtable.Count() };
}
身份证 | 项目 | 商店 | 地点 |
---|---|---|---|
1 | 苹果 | A家 | 04号线 |
2 | 芒果 | B栋 | 23号线 |
1 | 苹果 | A家 | 15号线 |
1 | 苹果 | B栋 | 08号线 |
3 | 香蕉 | A家 | 02号线 |
这是我尝试过的,但它没有显示任何内容。
[HttpGet]
public object Get()
{
return new { Items = _context.farmtable.GroupBy(x => x.Store, x => x.Item )
.Select(group => new { Store = group.Key, Item = group.Key, Items = group.ToList() })
.ToList(), Count = _context.farmtable.Count() };
}
预期产量
商店 | 项目 | 数 |
---|---|---|
A家 | 苹果 | 2 |
A家 | 香蕉 | 1 |
B栋 | 苹果 | 1 |
B栋 | 芒果 | 1 |
[HttpGet]
public object Get()
{
return _context.Farmtable.AsNoTracking()
.Select(x => new { Store = x.Store, Item = x.Item })
.GroupBy(g => new { g.Store, g.Item })
.Select(s => new { Store = s.Key.Store, Item = s.Key.Item, count = s.Count() });
}