多维关联数组C# [英] Multidimensional associative array C#

查看:90
本文介绍了多维关联数组C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从PHP的背景来看,我可以在PHP中做到这一点:

$array[sales_details][uid] = 1;
$array[sales_details][name] = "Name Surname";
$array[sales_details][sales][France][Paris] = 50;
$array[sales_details][sales][France][Lyon] = 25;
$array[sales_details][sales][UK][London] = 75;
$array[sales_details][sales][German][Berlin] = 23;

如何在C#中执行此操作?我试图研究字典.但是,即使我将value键定义为对象,它也不会接受"sales"数组.

var dict = new Dictionary<string, object>();
dict["uid"] = 1;
dict["sales"]["France"]["Paris"] = 50; //error kicks in here

使用C#可以吗?

解决方案

在我看来,您试图将很多信息放入一个数组中,实际上实际上是一个对象./p>

您可以使用锯齿形数组来解决此问题,但是对象是有效的方法更好.

创建一个这样的类:

public class SalesDetails
{
    public string Uid {get;set;}
    public string Name {get;set;}

    public List<SalesItem> SalesItems {get;set;} = new List<SalesItem>();
}

然后自己计算SalesItemCity和您需要的所有其他对象.

Coming from PHP background I could do this in PHP:

$array[sales_details][uid] = 1;
$array[sales_details][name] = "Name Surname";
$array[sales_details][sales][France][Paris] = 50;
$array[sales_details][sales][France][Lyon] = 25;
$array[sales_details][sales][UK][London] = 75;
$array[sales_details][sales][German][Berlin] = 23;

How can I do this in C#? I tried looking into Dictionary. But even if I define the value key as object it will not accept the "sales" array.

var dict = new Dictionary<string, object>();
dict["uid"] = 1;
dict["sales"]["France"]["Paris"] = 50; //error kicks in here

Is this possible with C#?

解决方案

It seems to me you are trying to put a lot of information in an array, what actually has to be an object.

You can solve this with jagged arrays, but objects are way better.

Create a class like this:

public class SalesDetails
{
    public string Uid {get;set;}
    public string Name {get;set;}

    public List<SalesItem> SalesItems {get;set;} = new List<SalesItem>();
}

Then work out yourself SalesItem, City and all other objects you need.

这篇关于多维关联数组C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆