使用 Linq 按可变整数范围分组 [英] Group by variable integer range using Linq

查看:26
本文介绍了使用 Linq 按可变整数范围分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试根据整数范围对一组数据进行分组,范围不以固定间隔增加.

I'm trying to group a set of data based on the range of an integer, by the range does not increase at a fixed interval.

例如我有

商品 ID 价格
1       10
2       30
3       50
4       120

Item ID Price
1          10
2          30
3          50
4          120

我想将价格在 0 - 10、11 - 100 和 100-500 之间的商品分组.所以项目1在A组中,项目2,3在B组中,项目4在C组中.

I would like to group the items with price 0 - 10, 11 - 100, and 100-500. So that item 1 is in group A, item 2,3, in group B, item 4 in group C.

我能想到的最接近的是从项目按 (items.price/10 ) 分组商品

The closest I can come up is from items group items by (items.price / 10 )

然后将组连接在一起以获得不同的范围.

then join the groups together to get the different ranges.

有什么想法吗?

推荐答案

参数化范围上限列表...

Parameterizing the list of range ceilings...

var ceilings = new[] { 10, 100, 500 };
var groupings = items.GroupBy(item => ceilings.First(ceiling => ceiling >= item));

这篇关于使用 Linq 按可变整数范围分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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