知道肯定這一點的唯一方法是看代碼,所以讓我們做...
您呼叫的List<T>
,反編譯的時候構造函數的實現,貌似
public List(IEnumerable<T> collection)
{
if (collection == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.collection);
ICollection<T> collection1 = collection as ICollection<T>;
if (collection1 != null)
{
int count = collection1.Count;
if (count == 0)
{
this._items = List<T>._emptyArray;
}
else
{
this._items = new T[count];
collection1.CopyTo(this._items, 0);
this._size = count;
}
}
else
{
this._size = 0;
this._items = List<T>._emptyArray;
foreach (T obj in collection)
this.Add(obj);
}
}
正如你所看到的,字典轉換爲ICollection<T>
,然後CopyTo
叫上這使我們Dictionary<TKey, TValue>
private void CopyTo(KeyValuePair<TKey, TValue>[] array, int index)
{
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
if (index < 0 || index > array.Length)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
if (array.Length - index < this.Count)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
int num = this.count;
Dictionary<TKey, TValue>.Entry[] entryArray = this.entries;
for (int index1 = 0; index1 < num; ++index1)
{
if (entryArray[index1].hashCode >= 0)
array[index++] = new KeyValuePair<TKey, TValue>(entryArray[index1].key, entryArray[index1].value);
}
}
從查看代碼中,字典的內部項目是,索引爲。
基於這些發現,如果你問是「會當它轉化爲一個泛型列表我的字典順序予以保留?」 - 那麼是的它會(根據.NET 4.0,這是我正在看的版本)。但是,問題在於,您實際上無法保證將項目的順序添加到字典開始。因此,我的建議將轉換爲使用OrderedDictionary<T>
之類的東西,或者在轉換它之前應用OrderBy
子句,例如
var list = new List<KeyValuePair<K, V>>(test.OrderBy(x => x.Value));
可能會有所幫助:http://stackoverflow.com/questions/7387874/is-there-a-an-easier-way-to-initialize-a-listkeyvaluepairt-u-like-a-dictio – Habib