簡體   English   中英

C#如何創建KeyValuePair的通用列表

[英]C# How to create a generic List of KeyValuePair

我創建了一個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。 還是有更好的方法來做到這一點?

使用KeyValuePair<string, object>使用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)));
));

如果要創建KeyValuePair列表,則應創建字典。

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM