如何将其附加到KeyValuePair

本文关键字:KeyValuePair | 更新日期: 2023-09-27 18:21:50

我的list显然返回了<string, string>。如何将第二个字符串附加到KeyValuePair中,并添加从第二个数据库调用中返回的ID?

    // Database calls here
    KeyValuePair<string, string> parks = new KeyValuePair<string, string>();
    DataSet dset = new DataSet();
    var list = new List<KeyValuePair<string, string>>();
    list.Add(new KeyValuePair<string, string>("Select one", "0"));
    foreach (DataRow row in ds.Tables[0].Rows)
    {
        //My database calls including:
         db.AddInParameter(comm, "@pID", DBType.Int32, row[1]);
         dset = db.ExecuteDataSet(comm);
         string attr = dset.Tables[0].Rows[0]["Value"].ToString();
        list.Add(new KeyValuePair<string, string>(row[0].ToString() + " - " + attr, row[1].ToString()));
    }
    return list;

如何将其附加到KeyValuePair

KeyValuePair<TKey, TValue>中的

键和值是只读的。你可以在工作中使用Dictionary<string,string>,并从中获得KeyValuePair<string, string>

我认为这是有效的:

// Database calls here
Dictionary<string, string> list = new Dictionary<string, string>();
list.Add("Select one", "0");
foreach (DataRow row in ds.Tables[0].Rows)
{
    list.Add(row[0].ToString(), row[1].ToString());
}
//Another database call that gets back an ID. I want to add/append this ID into my second string in my KeyValue Pair.
return list;

对于附加第二个字符串,可以使用list["/*Your ID*/"]= YourData;

List<KeyValuePair<TKey, TValue>>不是一个好方法。这就像你用一杯茶来生火一样

KeyValuePair<TKey, TValue>是不可变的。如果要坚持使用KeyValuePair<string, string>,则必须删除要修改的对,然后添加一个具有修改值的新对。

或者,使用不同的数据类型。如果要修改值,请使用允许修改值的类型。