C# How to create a generic List of KeyValuePair

13,621

Solution 1

If you want to create a KeyValuePair list, you should create Dictionary.

Dictionary<string, string> dic = new Dictionary<string,string>();
dic.Add("email", email);
dic.Add("password", password);
dic.Add("plan_id", planId.ToString());

Solution 2

Use KeyValuePair<string, object> to put values and create or convert the list to KeyValuePair<string, string> when to use FormUrlEncodedContent

Creating a new list

List<KeyValuePair<string, object>> keyValues = new List<KeyValuePair<string, object>>();

keyValues.Add(new KeyValuePair<string, object>("email", "asdasd"));
keyValues.Add(new KeyValuePair<string, object>("password", "1131"));
keyValues.Add(new KeyValuePair<string, object>("plan_id", 123));
keyValues.Add(new KeyValuePair<string, object>("other_field", null));

var content = new FormUrlEncodedContent(keyValues.Select(s => 
    new KeyValuePair<string, string>(s.Key, s.Value != null ? s.ToString() : null)
));

Convert list

public static KeyValuePair<string, string> ConvertRules(KeyValuePair<string, object> kv)
{
    return new KeyValuePair<string, string>(kv.Key, kv.Value != null ? kv.ToString() : null);
}

static Task Main(string[] args) 
{
    List<KeyValuePair<string, object>> keyValues = new List<KeyValuePair<string, object>>();

    keyValues.Add(new KeyValuePair<string, object>("email", "asdasd"));
    keyValues.Add(new KeyValuePair<string, object>("password", "1131"));
    keyValues.Add(new KeyValuePair<string, object>("plan_id", 123));
    keyValues.Add(new KeyValuePair<string, object>("other_field", null));

    var content = new FormUrlEncodedContent(keyValues.ConvertAll(ConvertRules)));
));
Share:
13,621
Yasitha
Author by

Yasitha

A Person who likes to contribute towards open source software.

Updated on June 04, 2022

Comments

  • Yasitha
    Yasitha almost 2 years

    I have created a list of KeyValuePair to populate the content as the data for the HttpClient.

    List<KeyValuePair<string, string>> keyValues = new List<KeyValuePair<string, string>>();
    
    keyValues.Add(new KeyValuePair<string, string>("email", email));
    keyValues.Add(new KeyValuePair<string, string>("password", password));
    keyValues.Add(new KeyValuePair<string, string>("plan_id", planId));
    
    var content = new FormUrlEncodedContent(keyValues);
    

    But later I found I have to send a int value as the plan_id. How can change the above list to accept KeyValuePair. Or is there any better way to do this?