c# - C# 中的多维关联数组
问题描述
开始从 JS 和 PHP 进入 C#。我已经习惯了对数据类型的严格使用,我正在努力弄清楚如何声明不同数据类型的多维关联数组。
例如,在 PHP 中可能会做这样的事情
$roomDiscount["apartment"][0]["minDaysOfStay"] = 10;
$roomDiscount["apartment"][0]["discount"] = 0.3;
$roomDiscount["apartment"][1]["minDaysOfStay"] = 15;
$roomDiscount["apartment"][1]["discount"] = 0.35;
$roomDiscount["apartment"][2]["minDaysOfStay"] = 16;
$roomDiscount["apartment"][2]["discount"] = 0.5;
$roomDiscount["presidential suite"][0]["minDaysOfStay"] = 10;
$roomDiscount["presidential suite"][0]["discount"] = 0.1;
$roomDiscount["presidential suite"][1]["minDaysOfStay"] = 15;
$roomDiscount["presidential suite"][1]["discount"] = 0.15;
$roomDiscount["presidential suite"][2]["minDaysOfStay"] = 16;
$roomDiscount["presidential suite"][2]["discount"] = 0.2;
到目前为止,我一直在努力使用字典
private static void SkiTripWithDictionariesArrays()
{
int daysOfStay = int.Parse(Console.ReadLine());
string typeOfAccomodation = Console.ReadLine().ToLower().Trim();
string review = Console.ReadLine().ToLower().Trim();
Dictionary<string, double> roomPrices = new Dictionary<string, double>();
Dictionary<string, object> roomDiscounts = new Dictionary<string, object>(); // <---- thats the bugger
Dictionary<string, double> reviewAdjustment = new Dictionary<string, double>();
//populate room prices
roomPrices.Add("room for one person", 18);
roomPrices.Add("apartment", 25);
roomPrices.Add("president apartment", 35);
}
解决方案
你当前的 PHP 代码是这样的:
$roomDiscount["apartment"][0]["minDaysOfStay"] = 10;
它接近 C# 中的这种结构:
Dictionary<string, List<Dictionary<string, double>>>
声明这样一个对象可能不是一个好方法。相反,您应该定义类对象。我在下面给出的示例仅用于说明目的,不一定是最好的方法(这种情况有很多不同的方法):
public class RoomDiscount
{
public int MinDaysOfStay {get;set;}
public double Discount {get;set;}
}
public class RoomDiscounts
{
public List<RoomDiscount> DiscountBands {get;set;}
}
用法:
Dictionary<string, RoomDiscounts> discountDetails = new Dictionary<string, RoomDiscounts>();
discountDetails["apartment"] = new RoomDiscounts {
DiscountBands = new List<RoomDiscount> {
new RoomDiscount {
MinDaysOfStay = 10,
Discount = 0.3
},
new RoomDiscount {
MinDaysOfStay = 15,
Discount = 0.35
},
new RoomDiscount {
MinDaysOfStay = 16,
Discount = 0.5
}
}
};
string room = "apartment";
int daysOfStay = 26;
double discount = discountDetails[room].DiscountBands.OrderByDescending(b => b.MinDaysOfStay).FirstOrDefault(b => daysOfStay >= b.MinDaysOfStay)?.Discount ?? 0;
同样,这只是您可以以更强类型的方式组织数据的一种方式的示例。请注意,如果未定义房间类型,这将引发异常,因此您可以使用TryGetValue
它从字典中检索详细信息。
推荐阅读
- angular - 模块在角度模块中没有导出成员错误
- kubernetes - Kubernetes coredns 就绪探测失败
- node.js - 引用尚未创建的模型,避免错误:关系“TABLENAME”不存在
- php - 尝试访问我的 api 平台时未找到 JWT 令牌 401 错误?
- react-native - react-native start 致命错误:区域分配失败 - 进程内存不足
- tensorflow - Tensorflow 错误 - tensorflow.python.framework.errors_impl.NotFoundError: /home/paperspace/nmt-chatbot/data/tst2012.from; 没有这样的文件或目录
- javascript - 如何验证异步函数中的对象数组?
- c# - 表达式体属性和简单的 Getter 属性之间的区别
- sharepoint - 有没有一种简单的方法来格式化(根据值设置颜色)共享点列而不编写任何 JSON 代码
- javascript - onClick 在 ReactJS 中不会触发