neuDev33
neuDev33

Reputation: 1623

Can Dictionary values be populated through a list without looping?

Can we have something like -

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;

Mostly, I want to know if there is a way to populate the keys and values by directly assigning them to a list?

Upvotes: 1

Views: 632

Answers (2)

jason
jason

Reputation: 241583

Mostly, I want to know if there is a way to populate the keys and values by directly assigning them to a list?

No, but just zip them and then use ToDictionary:

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

Upvotes: 5

Servy
Servy

Reputation: 203802

A dictionary, internally isn't storing the data as two lists. It's storing the data in a hash table, which means it need to take each key, generate a hash for it, and then place the item at the location that corresponding to that hash. Because of this the only way to add a group of items is just to loop through the group and add each item. You can use the LINQ ToDictionary method, as mentioned in another answer, but internally all it's going to do is loop through each item and add it to the dictionary. This prevents you from seeing the loop, but the loop is still there.

Upvotes: 1

Related Questions