将字典转换为两个列表的最佳方法

Best way to convert Dictionary to two lists

如何将 Dictionary<DateTime, double> 类型的字典转换为 Tuple<List<DateTime>, List<double>>

谢谢

编辑:以下是否保证两个列表中项目的顺序相同? var abc = new Tuple<List<DateTime>, List<double>>(_data.Keys.ToList(), _data.Values.ToList());

简单(保证顺序):

Tuple<List<DateTime>, List<double>> tuple 
                   = Tuple.Create(dict.Keys.ToList(), dict.Values.ToList());

the order of the values in the Dictionary.ValueCollection is unspecified, but it is the same order as the associated keys in the Dictionary.KeyCollection returned by the Keys property.

来源:MSDN

订单保证示例:

即使在更新、删除和添加之后也能保证订单。

Dictionary<int, string> dict = new Dictionary<int, string>();

dict[2] = "2";
dict[1] = "0";
dict[3] = "3";
dict[1] = "1";
dict[1] = "1";

dict.Remove(3);

var tuple = Tuple.Create(dict.Keys.ToList(), dict.Values.ToList());
// 2 1
// "2" "1"
var result = Tuple.Create(dict.Keys.ToList(), dict.Values.ToList());

根据您评论中的订单问题:

无法保证您会得到什么顺序,因为字典不是有序的集合。但它保证你在 Keys- 和 Values- 集合中得到相同的,如果你使用 foreach(KeyValuepair<DateTime,double> kv in dict).

MSDN: Keys:

The order of the keys in the Dictionary(Of TKey, TValue).KeyCollection is unspecified, but it is the same order as the associated values in the Dictionary(Of TKey, TValue).ValueCollection returned by the Values property.

MSDN: Values:

The order of the values in the Dictionary(Of TKey, TValue).ValueCollection is unspecified, but it is the same order as the associated keys in the Dictionary(Of TKey, TValue).KeyCollection returned by the Keys property.

您问过:

So, for example, dict[result.Item1[5]] == result.Item2[5] holds?

是的,根据上面的文档可以保证