簡體   English   中英

填充多維數組

[英]Fill a Multi-Dimensional Array

我有這樣的硬編碼的東西:

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

如果數據源由角色表和用戶表組成,我將如何填充該數組。 一個用戶可以具有多個角色。 不確定構造該代碼以支持類似內容的語法是什么。

為什么不在此處使用包含對象列表的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));
    }
}

您對數據結構有不同的選擇。 一個想法是為用戶提供一個類,並將角色存儲為每個用戶的列表

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);
                }
            }
        }
    }
}

(因此,您將使用適當的連接類型,讀取器類型等)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM