[英]C# How do I add the Value of a Dictionary to a variable based on its Key?
I have to calculate the price of an order based on the input from the user using a Dictionary, but I can't seem to get it right. 我必须根据用户使用Dictionary的输入来计算订单价格,但我似乎无法正确理解它。
For example, if the input is 236, the price of the order should be $8. 例如,如果输入为236,则订单价格应为$ 8。
Converting my LINQ query to double didn't work (my query is also definitely wrong). 将我的LINQ查询转换为double无效(我的查询也肯定是错误的)。 I don't really know any LINQ but as you can't really use a for loop for a dictionary as they aren't indexed, I don't really have any other choice. 我真的不知道任何LINQ,但是由于您不能为字典真正使用for循环,因为它们没有被索引,所以我真的没有其他选择。
Dictionary<int, double> items = new Dictionary<int, double>()
{
{ 1, 3.50 },
{ 2, 2.50 },
{ 3, 4.00 },
{ 4, 3.50 },
{ 5, 1.75 },
{ 6, 1.50 },
{ 7, 2.25 },
{ 8, 3.75 },
{ 9, 1.25 }
};
string order = Console.ReadLine();
double sum = 0;
for (int i = 0; i < order.Length; i++)
{
sum += Convert.ToDouble(items.Where(x => x.Key == int.Parse(order[i].ToString())).Select(x => x.Value));
}
Console.WriteLine(sum);
Console.ReadKey();
Well, the output should be the correct amount of dollars based on the input from the user. 嗯,输出应该是基于用户输入的正确金额。
无需循环。
var sum = order.Sum(c => items[int.Parse(c.ToString())]);
This implementation is quite fragile, it only allows 10 items and relies on string parsing but I think the following code does what you're asking: 此实现非常脆弱,它仅允许10个项目并且依赖于字符串解析,但是我认为以下代码可以满足您的要求:
order.Sum(character =>
{
int id = character - '0';
return items.TryGetValue(id, out double price) ? price : 0d;
});
TryGetValue
checks that order
only contains digits which are keys in the items dictionary. TryGetValue
检查order
仅包含数字,这些数字是项字典中的键。
尝试这个
order.Select(c => (c - '0')).Where(c => c > 0 && c < 10).Sum(c => items[c])
You can use sum += items[order[i]-'0'];
您可以使用sum += items[order[i]-'0'];
in your for loop. 在您的for循环中。
This works because '0' is stored with the value 48 (see the answers to this question ). 之所以有效,是因为'0'存储为值48(请参阅此问题的答案)。 The rest of the digits are stored in order ('1' is 49, '2' is 50, etc), so '1' - '0' == 1 and so forth. 其余数字按顺序存储(“ 1”为49,“ 2”为50,依此类推),因此“ 1”-“ 0” == 1。依此类推。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.