Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get dictionary values as a generic list

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

here the code :

Dictionary<string, List<MyType>> myDico = GetDictionary(); List<MyType> items = ??? 

I try :

List<MyType> items = new List<MyType>(myDico.values) 

But it does not work :-(

like image 687
Florian Avatar asked Sep 26 '11 13:09

Florian


People also ask

Is dictionary a generic collection?

In C#, Dictionary is a generic collection which is generally used to store key/value pairs. The working of Dictionary is quite similar to the non-generic hashtable. The advantage of Dictionary is, it is generic type. Dictionary is defined under System.

Can we use List as key in dictionary c#?

A relatively safe, simple, yet high performance technique for using lists as dictionary keys. Using collections as dictionary keys is sometimes necessary, but it can be a performance killer and unsafe. Here's how to make it faster and safer.

Can a dictionary have NULL values?

Dictionaries can't have null keys.


2 Answers

How about:

var values = myDico.Values.ToList(); 
like image 119
Slicedbread Avatar answered Nov 15 '22 13:11

Slicedbread


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(); 
like image 23
VdesmedT Avatar answered Nov 15 '22 14:11

VdesmedT