可以通过列表填充字典值而不循环吗?

neu*_*v33 1 c# dictionary

我们可以有类似的东西 -

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

List<string> keysList=  new List<string>();
List<string>valuesList=  new List<string>();

//Assuming both the list have the same number of items
dict.keys = keysList;
dict.values = valuesList;
Run Code Online (Sandbox Code Playgroud)

大多数情况下,我想知道是否有办法通过直接将它们分配给列表来填充键和值?

jas*_*son 5

大多数情况下,我想知道是否有办法通过直接将它们分配给列表来填充键和值?

不,但只需拉链然后使用ToDictionary:

var dict = keysList.Zip(valuesList, (key, value) => Tuple.Create(key, value))
                   .ToDictionary(pair => pair.Item1, pair => pair.Item2);
Run Code Online (Sandbox Code Playgroud)