如何使用列表添加项目到词典而不循环通过它?

时间:2011-02-02 21:53:18

标签: c# dictionary asp.net-4.0

我有这个词典 -

IDictionary<DateTime, int> kamptslist = new Dictionary<DateTime, int>();
List<int> listints= GetListofints(); //for values
List<int> listdates= GetListofdates();// for keys

我可以以某种方式将列表直接分配到词典而不是实际执行foreach并一次添加一个项目吗?

3 个答案:

答案 0 :(得分:6)

使用Enumerable.Zip将两个序列压缩在一起,然后使用Enumerable.ToDictionary

var kamptslist = listdates.Zip(listints, (d, n) => Tuple.Create(d, n))
                          .ToDictionary(x => x.Item1, x => x.Item2);

答案 1 :(得分:5)

您可以使用.NET 4轻松完成此操作:

var dictionary = listints.Zip(listdates, (value, key) => new { value, key })
                         .ToDictionary(x => x.key, x => x.value);

没有.NET 4,虽然你总是可以使用一个糟糕的黑客,但它有点困难:

var dictionary = Enumerable.Range(0, listints.Count)
                           .ToDictionary(i => listdates[i], i => listints[i]);

编辑:根据评论,这适用于明确键入的变量:

IDictionary<DateTime, int> kamptslist = 
     listints.Zip(listdates, (value, key) => new { value, key })
             .ToDictionary(x => x.key, x => x.value);

答案 2 :(得分:0)

IDictionary<DateTime, int> kamptslist = GetListofdates()
    .Zip(
        GetListofints(), 
        (date, value) => new { date, value })
    .ToDictionary(x => x.date, x => x.value);