[英]How to add items using Lists to Dictionary without looping through it?
我有這本字典-
IDictionary<DateTime, int> kamptslist = new Dictionary<DateTime, int>();
List<int> listints= GetListofints(); //for values
List<int> listdates= GetListofdates();// for keys
我能以某種方式將列表直接分配給字典,而不是實際進行一次foreach
並一次添加一項嗎?
使用Enumerable.Zip
將兩個序列壓縮在一起,然后使用Enumerable.ToDictionary
:
var kamptslist = listdates.Zip(listints, (d, n) => Tuple.Create(d, n))
.ToDictionary(x => x.Item1, x => x.Item2);
您可以使用.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);
IDictionary<DateTime, int> kamptslist = GetListofdates()
.Zip(
GetListofints(),
(date, value) => new { date, value })
.ToDictionary(x => x.date, x => x.value);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.