Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize dictionary with KeyValuePair

Tags:

c#

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?

like image 691
Rob Bowman Avatar asked Apr 22 '26 16:04

Rob Bowman


1 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

like image 179
OlegI Avatar answered Apr 24 '26 06:04

OlegI