首页 > 解决方案 > 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);

        }

标签: c#arraysmultidimensional-arrayassociative-array

解决方案


你当前的 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它从字典中检索详细信息。


推荐阅读