Convert Dictionary to an Array of KeyValue Collection [C#]

Here, I will try to load a dictionary into an array of a custom class (having a key/value pair) and also into the array of KeyValuePair.
Let’s say you have a class structure as the following:-

public class FieldValueAsTextEntity
{
    private string key;
    public string Key
    {
        get { return key; }
        set { key = value; }
    }

    private string value;
    public string Value
    {
        get { return this.value; }
        set { this.value = value; }
    }
}

Now to convert a Dictionary to the array of the class, FieldValueAsTextEntity, do the following:-


FieldValueAsTextEntity[] arrayCollection = dictionaryObject.Select(pair=> new FieldValueAsTextEntity()
{
	Key = pair.Key,
	Value = pair.Value
}).ToArray();

OR,

if you sinply want to get the Dictionary object into the array of KeyValuePair, then, do the following:-


KeyValuePair<string, string>[] lstStringCollection;
lstStringCollection = dictionaryObject.Select(pair => new KeyValuePair<string, string>(pair.Key, pair.Value)).ToArray();

NOTE: Here, we have passed the key & Value to the constructor of the KeyValuePair, as its Key & Value property is readonly.More info

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s