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

Vis*_*hal 1 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
Run Code Online (Sandbox Code Playgroud)

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

jas*_*son 6

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

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


Jon*_*eet 5

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

var dictionary = listints.Zip(listdates, (value, key) => new { value, key })
                         .ToDictionary(x => x.key, x => x.value);
Run Code Online (Sandbox Code Playgroud)

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

var dictionary = Enumerable.Range(0, listints.Count)
                           .ToDictionary(i => listdates[i], i => listints[i]);
Run Code Online (Sandbox Code Playgroud)

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

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