简体   繁体   English

通用字典值是通用字典

[英]Generic Dictionary value is an Generic Dictionary

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非常感谢

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();
    }
}
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.如果您预先知道K ,请使用DList方法。 If you want to use string , int etc for K , use the approach in DList2 .如果您想对K使用stringint等,请使用DList2中的方法。 The inner dictionary will work just fine with keys of type int , string , etc, even if its key is declared as object .内部字典适用于intstring等类型的键,即使它的键被声明为object

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM