Reputation: 194
In Powershell 2.0, how do I use C# 3.0 collection initializers ? (How to set collection inline?)
I've tried
$table= New-Object System.Data.DataTable {
TableName = "my table" ,
Columns = {
New-Object System.Data.DataColumn "col1",([string]) ,
New-Object System.Data.DataColumn "col2",([long]) ,
New-Object System.Data.DataColumn "col3",([datetime])
}
}
but $table has 0 columns after this bit of code.
I already know how to add columns to the Columns property of the DataTable class.. I would like to know how to do direct initialization of the collection.
Upvotes: 1
Views: 1431
Reputation: 201652
The C# collection initializer feature is not available in the PowerShell scripting language. PowerShell does have a feature that is close to the C# object initializer feature:
Add-Type -AssemblyName System.Windows.Forms
new-object system.drawing.point -property @{x = 1; y = 5}
In general, you will find that there are many features of C# that PowerShell doesn't have including no ternary operator (?:) or null coalescing opertor (??). There is no ability to implement new types much less types that inherit from another type. You will also find that PowerShell can do things that C# can't like offer a REPL experience, built-in syntax for hashtables @{}
, easy command-line parameter parsing with features like named, positional and optional parameters and support for binding parameters from pipeline input. They both have their strengths as well as things to like and dislike. :-)
If you'd like to see the collection initializer feature implemented in a future version of PowerShell, you can submit your suggestion on the Microsoft Connect site.
Upvotes: 1
Reputation: 43499
$table = New-Object system.Data.DataTable "my table"
$col1 = New-Object system.Data.DataColumn "col1",([string])
$col2 = New-Object system.Data.DataColumn "col2",([long])
$col3 = New-Object system.Data.DataColumn "col3",([datetime])
$table.columns.add($col1)
$table.columns.add($col2)
$table.columns.add($col3)
Upvotes: 0