Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize dictionary at declaration using PowerShell

Given this powershell code:

$drivers = New-Object 'System.Collections.Generic.Dictionary[String,String]' $drivers.Add("nitrous","vx") $drivers.Add("directx","vd") $drivers.Add("openGL","vo") 

Is it possible to initialize this dictionary directly without having to call the Add method. Like .NET allows you to do?

Something like this?

$foo = New-Object 'System.Collections.Generic.Dictionary[String,String]'{{"a","Alley"},{"b" "bat"}} 

[not sure what type of syntax this would involve]

like image 416
C Johnson Avatar asked Jul 20 '11 16:07

C Johnson


People also ask

How do you declare a dictionary in PowerShell?

You can create an ordered dictionary by adding an object of the OrderedDictionary type, but the easiest way to create an ordered dictionary is use the [ordered] attribute. The [ordered] attribute is introduced in PowerShell 3.0. Place the attribute immediately before the "@" symbol.

Is there a dictionary in PowerShell?

PowerShell Dictionary is also known as Hashtable or associate array is a compact data structure and composed of the key and the value pair. Hashtable is a . Net namespace System. Collections.

What is @{} in PowerShell?

@{} in PowerShell defines a hashtable, a data structure for mapping unique keys to values (in other languages this data structure is called "dictionary" or "associative array"). @{} on its own defines an empty hashtable, that can then be filled with values, e.g. like this: $h = @{} $h['a'] = 'foo' $h['b'] = 'bar'


1 Answers

No. The initialization syntax for Dictionary<TKey,TValue> is C# syntax candy. Powershell has its own initializer syntax support for System.Collections.HashTable (@{}):

$drivers = @{"nitrous"="vx"; "directx"="vd"; "openGL"="vo"}; 

For [probably] nearly all cases it will work just as well as Dictionary<TKey,TValue>. If you really need Dictionary<TKey,TValue> for some reason, you could make a function that takes a HashTable and iterates through the keys and values to add them to a new Dictionary<TKey,TValue>.


The C# initializer syntax isn't exactly "direct" anyway. The compiler generates calls to Add() from it.

like image 132
Joel B Fant Avatar answered Sep 28 '22 21:09

Joel B Fant