C#如何创建KeyValuePair的通用List

问题描述 投票:0回答:3

我创建了一个KeyValuePair列表来填充内容作为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);

但后来我发现我必须发送一个int值作为plan_id。如何更改上面的列表以接受KeyValuePair。或者有更好的方法吗?

c# list generics httpclient keyvaluepair
3个回答
0
投票

如果要创建KeyValuePair列表,则应创建Dictionary。

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

0
投票

不要使用List<KeyValuePair<string,string>>,而不是Dictionary<string, string>。使用planId.ToString()。


0
投票

使用KeyValuePair<string, object>放置值并创建或转换列表到KeyValuePair<string, string>何时使用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)));
));
© www.soinside.com 2019 - 2024. All rights reserved.