I have List<String>
, i need to convert it to Dictionary<int,String>
with auto generation of Key, is any shortest way to accomplish that? I have tried:
var dictionary = new Dictionary<int, String>(); int index = 0; list.ForEach(x=>{ definitions.Add(index, x); index++; });
but i think it is dirty way.
Since python dictionary is unordered, the output can be in any order. To convert a list to dictionary, we can use list comprehension and make a key:value pair of consecutive elements. Finally, typecase the list to dict type.
Convert List to Dictionary Using the Non-Linq Method in C# We can also convert a list to a dictionary in a non-LINQ way using a loop. It is advised to use the non-LINQ method because it has improved performance, but we can use either method according to our preferences.
var dict = list.Select((s, i) => new { s, i }).ToDictionary(x => x.i, x => x.s);
I find this to be the neatest
int index = 0; var dictionary = myList.ToDictionary(item => index++);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With