How to get dictionary values as a generic list

前端 未结 10 1575
傲寒
傲寒 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:00

    Another variation you could also use

    MyType[] Temp = new MyType[myDico.Count];
    myDico.Values.CopyTo(Temp, 0);
    List<MyType> items = Temp.ToList();
    
    0 讨论(0)
  • 2020-12-24 05:01
    Dictionary<string, MyType> myDico = GetDictionary();
    
    var items = myDico.Select(d=> d.Value).ToList();
    
    0 讨论(0)
  • 2020-12-24 05:03

    Going further on the answer of Slaks, if one or more lists in your dictionary is null, a System.NullReferenceException will be thrown when calling ToList(), play safe:

    List<MyType> allItems = myDico.Values.Where(x => x != null).SelectMany(x => x).ToList();
    
    0 讨论(0)
  • 2020-12-24 05:08

    Off course, myDico.Values is List<List<MyType>>.

    Use Linq if you want to flattern your lists

    var items = myDico.SelectMany (d => d.Value).ToList();
    
    0 讨论(0)
  • 2020-12-24 05:11

    You probably want to flatten all of the lists in Values into a single list:

    List<MyType> allItems = myDico.Values.SelectMany(c => c).ToList();
    
    0 讨论(0)
  • 2020-12-24 05:11

    Another variant:

        List<MyType> items = new List<MyType>();
        items.AddRange(myDico.values);
    
    0 讨论(0)
提交回复
热议问题