[英]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 :-( 但它不起作用:-(
怎么样:
var values = myDico.Values.ToList();
Off course, myDico.Values is List<List<MyType>>
. 当然,myDico.Values是
List<List<MyType>>
。
Use Linq if you want to flattern your lists 如果要平展列表,请使用Linq
var items = myDico.SelectMany (d => d.Value).ToList();
Another variant: 另一个变种:
List<MyType> items = new List<MyType>();
items.AddRange(myDico.values);
您可能希望将Values
所有列表展平为单个列表:
List<MyType> allItems = myDico.Values.SelectMany(c => c).ToList();
我的OneLiner:
var MyList = new List<MyType>(MyDico.Values);
进一步研究Slaks的答案,如果你的字典中的一个或多个列表为null,则在调用ToList()
时会抛出System.NullReferenceException
,安全地播放:
List<MyType> allItems = myDico.Values.Where(x => x != null).SelectMany(x => x).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 variation you could also use 您也可以使用另一种变体
MyType[] Temp = new MyType[myDico.Count];
myDico.Values.CopyTo(Temp, 0);
List<MyType> items = Temp.ToList();
Dictionary<string, MyType> myDico = GetDictionary();
var items = myDico.Select(d=> d.Value).ToList();
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.