如何获取字典值作为通用列表

我只是想从 Dictionary 的值中得到一个列表,但它并不像看起来那么简单!

这里是密码:

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

我试着:

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

但它不起作用:

174666 次浏览

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);

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

List<MyType> allItems = myDico.Values.SelectMany(c => c).ToList();

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();
        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);

Another variant:

List<MyType> items = new List<MyType>();
items.AddRange(myDico.Values);

Another variation you could also use

MyType[] Temp = new MyType[myDico.Count];
myDico.Values.CopyTo(Temp, 0);
List<MyType> items = Temp.ToList();

My OneLiner:

var MyList = new List<MyType>(MyDico.Values);
Dictionary<string, MyType> myDico = GetDictionary();


var items = myDico.Select(d=> d.Value).ToList();

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();

How about:

var values = myDico.Values.ToList();