C#如何创建一个泛型KeyValuePair列表

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?或者有更好的方法吗?


4
最终在HTTP中发送的所有内容都是ASCII字符串,因此为什么不直接调用 planId.ToString(CultureInfo.InvariantCulture) - Dai
我正在调用一个外部API。当我发送一个字符串值作为计划ID时,我收到了一个错误请求。但是使用整数值却成功了。 - Yasitha
在Java中是否可以创建以下通用列表。List<KeyValuePair<string, T>> keyValues = new List<KeyValuePair<string, T>>(); - Yasitha
1
好的,FormUrlEncodedContent 只接受 IEnumerable<KeyValuePair<string, string>> nameValueCollection,所以除非你以不同的方式编码你的内容,否则你必须这样做。正如 @Dai 所提到的,将你的整数转换为字符串表示形式。 - Alex
谢谢@Dai和Alex。那个有效。 - Yasitha
3个回答

4
如果你想创建一个KeyValuePair列表,你需要创建Dictionary。
Dictionary<string, string> dic = new Dictionary<string,string>();
dic.Add("email", email);
dic.Add("password", password);
dic.Add("plan_id", planId.ToString());

这里需要创建的是类似于Java中的通用ArrayList。List<KeyValuePair<string, T>> keyValues = new List<KeyValuePair<string, T>>(); - Yasitha
1
此解决方案不允许重复! - Flimtix

4

当你需要使用FormUrlEncodedContent时,用KeyValuePair<string, object>来放置值,并且创建转换列表为KeyValuePair<string, string>

创建新的列表

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)
));

转换列表

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)));
));

0

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接