Nested Dictionary collection in .NET

后端 未结 6 1986
伪装坚强ぢ
伪装坚强ぢ 2020-12-17 06:42

The .NET Dictionary object allows assignment of key/values like so:

Dictionary dict = new Dictionary&l         


        
6条回答
  •  南方客
    南方客 (楼主)
    2020-12-17 07:40

    You have to decide on either supporting a fixed number of string keys to look up, or provide a more general key mechanism if the number of keys can vary. For the first case try the following:

    Dictionary> dict =
        Dictionary>();
    dict["F1"]["F2"] = "foo";
    Dictionary>> dict2 =
        Dictionary>();
    dict2["F1"]["F2"]["F3"] = "bar";
    

    For the second case, you could do the following:

    Dictionary dict = new Dictionary(new MyEqualityComparer());
    dict[new string[] {"F1","F2"}] = "foo";
    dict[new string[] {"F1","F2","F3"}] = "bar";
    

    where the class MyEqualityComparer would be something like:

    public class MyEqualityComparer : IEqualityComparer
    {
        public int GetHashCode(string[]item)
        {
             int hashcode = 0;
             foreach (string s in item)
             { 
                 hashcode |= s.GetHashCode();
             }
             return hashcode;
        }
    
        public bool Equals(string [] a, string [] b)
        {
             if (a.Length != b.Length)
                 return false;
             for (int i = 0; i < a.Length; ++i)
             {
                 if (a[i] != b[i])
                     return false;
             }
             return true;
       }
    

提交回复
热议问题