I'd like to create a class which contains a generic dictionary which value is an generic dictionary as below:
class DList<T>
{
public Dictionary<string, Dictionary<K, T>> Dic;
public Init<K,T>()
{
Dic = new Dictionary<string, Dictionary<K, T>>();
Dic.Add("Name", new Dictionary<string, T>());
Dic.Add("Id", new Dictionary<int, T>());
}
}
How can I implement this? Thanks a lot
CodePudding user response:
dynamic works. What I need is almost like a multi-keys Dictionary.
public class DList<T> : IEnumerable
{
private List<T> list;
private Dictionary<string, dynamic> dic;
public T this[int i] => list[i];
public dynamic this[string j] => dic[j];
public int Count => list.Count;
public DList(params string[] properties)
{
this.list = new List<T>();
this.dic = new Dictionary<string, dynamic>();
foreach (var item in properties)
{
this.dic.Add(item, new Dictionary<dynamic, T>());
}
}
public void Add(T t)
{
list.Add(t);
foreach (var item in dic)
{
dynamic d = t.GetType()
.GetField(item.Key)
.GetValue(t);
if (item.Value.ContainsKey(d))
continue;
item.Value.Add(d, t);
}
}
public T Get(string key, dynamic s)
{
return dic[key][s];
}
public T Get(int index)
{
return list[index];
}
public void Clear()
{
this.list.Clear();
foreach(var item in dic)
{
item.Value.Clear();
}
}
public void Sort(Comparison<T> Compare)
{
list.Sort(Compare);
}
public IEnumerator GetEnumerator()
{
return list.GetEnumerator();
}
}
CodePudding user response:
class DList<K, T>
{
public Dictionary<string, Dictionary<K, T>> Dic;
public DList()
{
Dic = new Dictionary<string, Dictionary<K, T>>();
Dic.Add("Name", new Dictionary<K, T>());
Dic.Add("Id", new Dictionary<K, T>());
}
}
class DList2<K, T>
{
public Dictionary<string, Dictionary<object, T>> Dic;
public DList2()
{
Dic = new Dictionary<string, Dictionary<object, T>>();
Dic.Add("Name", new Dictionary<object, T>());
Dic.Add("Id", new Dictionary<object, T>());
}
}
If you know K
upfront, use the DList
approach. If you want to use string
, int
etc for K
, use the approach in DList2
. The inner dictionary will work just fine with keys of type int
, string
, etc, even if its key is declared as object
.