C#多维数组

问题描述 投票:-1回答:1

我正在尝试开发一个使用网站数据库的桌面应用程序(winforms)。我目前正在研究本地数据库,以避免在开发过程中浪费主机流量。

我遇到了一个场景,我花了2天时间用谷歌搜索,无法找到有关如何实现特殊类型数组的具体答案。

目前我正在尝试从数据库中检索用户信息作为数组,但我需要一些项目也是一个数组,而其他项目保持为字符串。

在PHP中我使用类似的东西:

$user["username"] = $result["username"];
$user["name"] = $result["name"];
$user["lastname"] = $result["lastname"];

等等。问题来自查询从数据库中检索电话号码,因为大多数用户至少有2个号码(家庭和小区)

foreach ($phones as $type => $phone) {
  $user["phone"][$type] = $phone;
}

$ type是手机的类型(主线,主单元,工作单元,寻呼机等),$ phone包含该号码。所以,就我搜索过,以及我读过的所有内容,我都学到了这一点

Dictionary<string, string>可以使用第一个字符串作为数组键,第二个数组值,但第二个字符串不能转换为数组Dictionary<string, List<string>>可以使第二级数组,但不能存储字符串作为值。 (Can't convert 'string' into 'System.Collections.Generic.List<string>'

那么,实现这一特定场景的最佳方式是什么?如何使数组保存字符串和数组数据?

c# list dictionary multidimensional-array
1个回答
1
投票

处理此任务的更好方法是结构数组

public struct DatabaseNode
    {
        public string Username;
        public string Name;
        public string Lastname;
        public Dictionary<string,string> Phones;

        public DatabaseNode(string user,string name,string lastname,string housephone)
        {
            Username = user;
            Name = name;
            Lastname = lastname;
            Phones = new Dictionary<string, string>();
            Phones.Add("House", housephone);
        }

        public void Add_Phone(string type,string num)
        {
            Phones.Add(type, num);
        }
    }

使用这个可以很容易地拥有一个DatabaseNode数组并存储不同的数据,甚至在必要时使用之前转换数据。

© www.soinside.com 2019 - 2024. All rights reserved.