填充多维数组

时间:2012-03-15 13:58:49

标签: c# arrays multidimensional-array

我有类似硬编码的东西:

private string[,] m_RolesForUser = new string[,] {
    {"John","President,Chair"},
    {"Lisa","Chair"},    
    {"Mike","Executive,President,Chair"},
};

如果数据源由角色表和用户表组成,我将如何填充此数组。用户可以拥有多个角色。不确定构造代码以支持这样的语法是什么语法。

2 个答案:

答案 0 :(得分:4)

为什么不在这里使用Dictionary对象列表? C#是一种OO语言,因此使用对象是更优选的。下面的示例使用字符串来适合您的示例,但您甚至可以创建一个Person类和一个Role类,并将Person绑定到Role个列表

private Dictionary<string, List<string>> roles = new Dictionary
    {
        {"John", new List{"President","Chair"}},
        {"Lisa", new List{"Chair"}},    
        {"Mike", new List{"Executive","President","Chair"}}
    }

寻找Lisa的角色:

//Just verifying that Lisa exists.
//If you try to access a non-existent key you will get an exception
var roleLookingFor = "Lisa";
if(roles.Contains(roleLookingFor))
{
    foreach(var role in roles[roleLookingFor])
    {
        Console.Out.WriteLine(String.Format("{0} is in role '{1}'.", 
                                               roleLookingFor, role));
    }
}

答案 1 :(得分:1)

您有不同的数据结构选项。一个想法是为用户创建一个类,并将角色存储为每个用户的列表

public class User
{
    public User ()
    {
        Roles = new List<string>();
    }

    public int ID { get; set; }
    public string Name { get; set; }

    public List<string> Roles { get; private set; }
}

然后你可以有一个用户列表

List<User> _users = new List<User>();

如果您想为每个角色存储更多信息,您可以拥有一个Role类以及每个角色的用户列表。

List<T>与数组的优势在于列表会动态增长。

像这样填写这个结构

using (OleDbConnection cnn = new OleDbConnection(ConnectionString)) {
    string query = "SELECT ... FROM users LEFT JOIN user_roles ON ... ORDER BY UserID";
    using (OleDbCommand cmd = new OleDbCommand(query, cnn)) {
        cnn.Open();
        using (OleDbDataReader reader = cmd.ExecuteReader()) {
            int userIdOrdinal = reader.GetOrdinal("UserID");
            int userNameOrdinal = reader.GetOrdinal("UserName");
            int roleIdOrdinal = reader.GetOrdinal("RoleID");
            int roleNameOrdinal = reader.GetOrdinal("RoleName");
            User user = null;
            while (reader.Read()) {
                int userID = reader.GetInt32(userIdOrdinal);
                if (user == null || user.ID != userID) {
                    user = new User { ID = userID };
                    user.Name =  reader.GetString(userNameOrdinal);
                    _users.Add(user);
                }
                if (!reader.IsDBNull(roleIdOrdinal)) {
                    user.Roles.Add(reader.GetString(roleNameOrdinal);
                }
            }
        }
    }
}

(因为你会使用适当的连接类型,读者类型等)