Initialize dictionary with KeyValuePair

Viewed 4547

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?

4 Answers

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

You can always just extract the kvp to a variable and use that, so the method won't be called twice.

var kvp = ams.GetKVP(AvaloqTypes.Person.PersonDocm.DocmItem);
AdditionalProperties = new Dictionary<string,object>() { { kvp.Key, kvp.Value } }

But I would question the choice of using kvp in this case or the dictionary if there is just one kvp?

Other options

AdditionalProperties = new Dictionary<string,object>(new List<KeyValuePair<string, object>> { ams.GetKVP(AvaloqTypes.Person.PersonDocm.DocmItem) });

Actually there is a Add-Method you can use, which takes a KeyPairValue as a parameter.

The problem: It is a explicit implementation of the ICollection Add-Method.

That means you can only call it by casting your Dictionary to a ICollection or any interface that inherits ICollection and is implemented by Dictionary.

And there is a interface which does exactly that and exposes the functionality of the Dictionary-Type: IDictionary

So by defining AdditionalProperties as IDictionary<string, object> AdditionalProperties you can do:

AdditionalProperties = new Dictionary<string,object>();
AdditionalProperties.Add(ams.GetKVP(AvaloqTypes.Person.PersonDocm.DocmItem));
Related