Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use a collection initializer for Dictionary<TKey, TValue> entries?

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?

like image 240
Gerrie Schenck Avatar asked Jan 30 '09 10:01

Gerrie Schenck


People also ask

Can we store null value in dictionary?

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 .

How do you check if a dictionary contains a key C#?

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.

What is collection initializers in C#?

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.

Does dictionary guarantee order?

Changed in version 3.7: Dictionary order is guaranteed to be insertion order. This behavior was an implementation detail of CPython from 3.6.


2 Answers

var names = new Dictionary<int, string> {   { 1, "Adam" },   { 2, "Bart" },   { 3, "Charlie" } }; 
like image 154
bruno conde Avatar answered Sep 21 '22 04:09

bruno conde


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!" }; 
like image 21
Anton Gogolev Avatar answered Sep 19 '22 04:09

Anton Gogolev