I want to use a collection initializer for the next bit of code:
public Dictionary<int, string> GetNames() { Dictionary<int, string> names = new Dictionary<int, string>(); names.Add(1, "Adam"); names.Add(2, "Bart"); names.Add(3, "Charlie"); return names; }
So typically it should be something like:
return new Dictionary<int, string> { 1, "Adam", 2, "Bart" ...
But what is the correct syntax for this?
null cannot be used as key in a dictionary, because you need a hashcode of the key. And the key must be unique. So you could replace null with some magic value, but it still would crash if you have multiple rows where the key is null .
Syntax: public bool ContainsKey (TKey key); Here, the key is the Key which is to be located in the Dictionary. Return Value: This method will return true if the Dictionary contains an element with the specified key otherwise, it returns false.
Collection initializers let you specify one or more element initializers when you initialize a collection type that implements IEnumerable and has Add with the appropriate signature as an instance method or an extension method. The element initializers can be a simple value, an expression, or an object initializer.
Changed in version 3.7: Dictionary order is guaranteed to be insertion order. This behavior was an implementation detail of CPython from 3.6.
var names = new Dictionary<int, string> { { 1, "Adam" }, { 2, "Bart" }, { 3, "Charlie" } };
The syntax is slightly different:
Dictionary<int, string> names = new Dictionary<int, string>() { { 1, "Adam" }, { 2, "Bart" } }
Note that you're effectively adding tuples of values.
As a sidenote: collection initializers contain arguments which are basically arguments to whatever Add() function that comes in handy with respect to compile-time type of argument. That is, if I have a collection:
class FooCollection : IEnumerable { public void Add(int i) ... public void Add(string s) ... public void Add(double d) ... }
the following code is perfectly legal:
var foos = new FooCollection() { 1, 2, 3.14, "Hello, world!" };
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