Within initialisation of a large object that contains many different types of child object...
I have a function that returns a KeyValuePair<string, object>. I would like to call this when initialising a Dictionary<string, object>, something like this:
AdditionalProperties = new Dictionary<string,object>(ams.GetKVP(AvaloqTypes.Person.PersonDocm.CountryId))
This gives a compilation error that "cannot convert from KeyValuePair to IDictionary"
I can work-around this as follows:
AdditionalProperties = new Dictionary<string,object>()
{
{ ams.GetKVP(AvaloqTypes.Person.PersonDocm.DocmItem).Key,
ams.GetKVP(AvaloqTypes.Person.PersonDocm.DocmItem).Value
}
}
However, this means the GetKVP method is called twice.
Is there a better solution that doesn't involve changing the GetKVP method?
There is no constructor overloading for Dictionary which takes IKeyValuePair as an argument. But you can pass a collection of KeyValuePair when instantiating new Dictionary:
var kvp = new Dictionary<string,object>(new []
{
ams.GetKVP(AvaloqTypes.Person.PersonDocm.CountryId)
});
EDIT: This constructor exists only in .NET Core
link
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