You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C#控制台应用中按价格区间分组展示产品

按价格区间分组展示产品列表

实现思路

  • 先遍历产品列表,找到最高价格,以此计算需要划分的区间数量(区间步长固定为100)
  • 对每个区间,筛选出价格落在该区间内的产品
  • 按照要求的格式在控制台输出分组结果

代码示例(JavaScript)

假设你的产品列表结构如下:

const products = [
  { id: 1, name: "产品A", price: 50 },
  { id: 2, name: "产品B", price: 150 },
  { id: 3, name: "产品C", price: 220 },
  { id: 4, name: "产品D", price: 80 },
  { id: 5, name: "产品E", price: 280 },
];

实现分组与控制台输出的代码:

// 1. 获取产品中的最高价格
const maxPrice = Math.max(...products.map(p => p.price));
// 2. 计算总区间数(向上取整,确保覆盖最高价格)
const totalIntervals = Math.ceil(maxPrice / 100);

// 3. 遍历每个区间,筛选产品并输出
for (let i = 0; i < totalIntervals; i++) {
  const start = i * 100 + 1;
  const end = (i + 1) * 100;
  // 筛选当前区间内的产品
  const intervalProducts = products.filter(p => p.price >= start && p.price <= end);
  
  // 输出区间标题
  console.log(`价格${start}-${end}`);
  // 输出对应产品列表
  if (intervalProducts.length > 0) {
    intervalProducts.forEach(p => {
      console.log(`--${p.name}(ID: ${p.id},价格: ${p.price})`);
    });
  } else {
    console.log("--无对应产品");
  }
  console.log(""); // 空行分隔不同区间
}

代码关键说明

  • Math.max(...products.map(p => p.price)):提取所有产品价格后快速获取最大值
  • Math.ceil(maxPrice / 100):通过向上取整计算区间数,比如最高价格280会生成3个区间(1-100、101-200、201-300)
  • 循环中通过start和end定义当前区间的价格范围,用filter筛选对应产品,最后按格式输出

Python版本代码示例

如果使用Python实现,代码如下:

products = [
    {"id": 1, "name": "产品A", "price": 50},
    {"id": 2, "name": "产品B", "price": 150},
    {"id": 3, "name": "产品C", "price": 220},
    {"id": 4, "name": "产品D", "price": 80},
    {"id": 5, "name": "产品E", "price": 280},
]

# 获取最高价格
max_price = max(p["price"] for p in products)
# 计算总区间数(整数运算实现向上取整)
total_intervals = (max_price + 99) // 100

for i in range(total_intervals):
    start = i * 100 + 1
    end = (i + 1) * 100
    # 筛选当前区间的产品
    interval_products = [p for p in products if start <= p["price"] <= end]
    
    print(f"价格{start}-{end}")
    if interval_products:
        for p in interval_products:
            print(f"--{p['name']}(ID: {p['id']},价格: {p['price']})")
    else:
        print("--无对应产品")
    print()  # 空行分隔区间

内容的提问来源于stack exchange,提问作者niler

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 20:01:11