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

时间:2016-07-08 09:16:53

标签: c# list dictionary ienumerable

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

由于

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

2 个答案:

答案 0 :(得分:5)

简单(订单有保证):

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

未指定Dictionary.ValueCollection中的值的顺序,但它的顺序与   Dictionary.KeyCollection中的关联键   由Keys属性返回。

来源: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"

答案 1 :(得分:2)

var result = Tuple.Create(dict.Keys.ToList(), dict.Values.ToList());

根据评论中的订单问题:

由于字典不是有序集合,因此无法保证您获得的顺序。但是,我们保证您在KeysValues - 集合中获得相同的内容,如果您使用foreach(KeyValuepair<DateTime,double> kv in dict)

MSDN: Keys

  

Dictionary中的键的顺序(Of TKey,TValue).KeyCollection   未指定,但它与相关值的顺序相同   字典(Of TKey,TValue).ValueCollection由值返回   属性。

MSDN: Values

  

中的值的顺序   字典(Of TKey,TValue).ValueCollection未指定,但确实如此   与相关键的顺序相同   字典(Of TKey,TValue).KeyCollection由Keys返回   属性。

你问过:

  

那么,例如,dict[result.Item1[5]] == result.Item2[5]成立了吗?

是的,根据上述文档保证

相关问题