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

如何根据输入的零件名提取并行数组中的对应价格与人工成本

根据零件名称提取对应价格与人工成本的实现方案

直接基于现有数组的实现方式

你可以通过Array.IndexOf方法找到输入零件名在PartName数组中的索引,再用该索引从Price和Labor数组中取出对应值,具体代码如下:

// 模拟用户输入的零件名称
string inputPart = "TIRES";

// 获取零件名称在数组中的索引
int partIndex = Array.IndexOf(PartName, inputPart);

// 检查索引有效性(避免找不到零件的情况)
if (partIndex != -1)
{
    decimal selectedPrice = Price[partIndex];
    decimal selectedLabor = Labor[partIndex];
    
    // 此处可将两个值用于后续总计计算
    Console.WriteLine($"选中零件价格:{selectedPrice:C},人工成本:{selectedLabor:C}");
}
else
{
    Console.WriteLine("未查询到该零件的相关信息");
}

更健壮的优化方案(推荐)

使用多个平行数组维护数据易出现顺序不一致、长度不匹配的问题,建议将零件信息封装成类,用集合管理:

1. 定义零件类

public class AutoPart
{
    public string Name { get; set; }
    public decimal Price { get; set; }
    public decimal LaborCost { get; set; }
}

2. 初始化零件集合

List<AutoPart> autoParts = new List<AutoPart>
{
    new AutoPart { Name = "WIPERBLADES", Price = 20.00m, LaborCost = 5.00m },
    new AutoPart { Name = "TIRES", Price = 520.00m, LaborCost = 40.00m },
    new AutoPart { Name = "BATTERY", Price = 118.99m, LaborCost = 25.99m },
    new AutoPart { Name = "OIL", Price = 21.50m, LaborCost = 9.99m },
    new AutoPart { Name = "OILFILTER", Price = 8.49m, LaborCost = 7.00m }
};

3. 根据名称查询零件信息

string inputPart = "OIL";
// 支持忽略大小写查询,可按需调整匹配规则
var targetPart = autoParts.FirstOrDefault(p => p.Name.Equals(inputPart, StringComparison.OrdinalIgnoreCase));

if (targetPart != null)
{
    decimal partPrice = targetPart.Price;
    decimal laborCost = targetPart.LaborCost;
    
    // 后续总计计算逻辑
    Console.WriteLine($"零件价格:{partPrice:C},人工成本:{laborCost:C}");
}
else
{
    Console.WriteLine("未找到指定零件");
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 06:57:09