nightroman / Mdbc

MongoDB Cmdlets for PowerShell
Apache License 2.0
141 stars 16 forks source link

"Get-MdbcData -As" for a case insensitive hashtable #47

Closed ssdiz closed 3 years ago

ssdiz commented 3 years ago

Hello, I would like to get a case insensitive hashtable returned via "Get-MdbcData -As" but I can't figure out how to do it as I can't seem to specify constructors to the object type provide to Param As.

This is how I construct case insensitive hashtables in powershell besides just using the default [hashtable]:

I can cast the case sensitive hashtable to insensitive after using Param As Hashtable but I would rather not create the hashtable then convert for performance reasons.

Do you have any suggestions on how to accomplish this?

Regards, Scott

nightroman commented 3 years ago

Interesting question.

The parameter As requires a type with the default constructor. Unfortunately, the Hashtable default constructor is not what you need. Fortunately, you may derive from Hashtable and make its default constructor up to you.

Like this, for example:

class MyHashtable : System.Collections.Hashtable {
    MyHashtable() : base([System.StringComparer]::OrdinalIgnoreCase) {}
}

Import-Module Mdbc

Connect-Mdbc -NewCollection
@{_id = 1; n = 1} | Add-MdbcData
$r = Get-MdbcData -As ([MyHashtable])

# this 'N' is the same as 'n'
$r.N = 2
$r

The above code is for PowerShell 5 with classes. In older versions use Add-Type with a similar piece of C# code.

ssdiz commented 3 years ago

Great!

I was on to the same solution but my c# code was half working and I was getting this error:

Invoke-MdbcAggregate : GenericArguments[0], 'CaseInsensitiveHashtable', on 'MongoDB.Bson.Serialization.Serializers.DictionaryInterfaceImplementerSerializer`1[TDictionary]' violates the constraint of type 'TDictionary'.

Since your response, I have successfully tested your solution with the PS class and modified the c# to work.

I am ultimately trying to make the returned data more powershell friendly but without the cost to create [pscustomobject].

Thanks for the assistance and quick response.