How to get dictionary values as a generic list

前端 未结 10 1576
傲寒
傲寒 2020-12-24 04:45

I just want get a list from Dictionary values but it\'s not so simple as it appears !

here the code :

Dictionary> my         


        
相关标签:
10条回答
  • 2020-12-24 05:12

    Use this:

    List<MyType> items = new List<MyType>()
    foreach(var value in myDico.Values)
        items.AddRange(value);
    

    The problem is that every key in your dictionary has a list of instances as value. Your code would work, if each key would have exactly one instance as value, as in the following example:

    Dictionary<string, MyType> myDico = GetDictionary();
    List<MyType> items = new List<MyType>(myDico.Values);
    
    0 讨论(0)
  • 2020-12-24 05:16

    How about:

    var values = myDico.Values.ToList();
    
    0 讨论(0)
  • 2020-12-24 05:19
            List<String> objListColor = new List<String>() { "Red", "Blue", "Green", "Yellow" };
            List<String> objListDirection = new List<String>() { "East", "West", "North", "South" };
    
            Dictionary<String, List<String>> objDicRes = new Dictionary<String, List<String>>();
            objDicRes.Add("Color", objListColor);
            objDicRes.Add("Direction", objListDirection);
    
    0 讨论(0)
  • 2020-12-24 05:21

    My OneLiner:

    var MyList = new List<MyType>(MyDico.Values);
    
    0 讨论(0)
提交回复
热议问题