2012-01-30 69 views
2

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

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

回答

2

in 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>>不是好办法。就像你喝了一杯茶来熄火!

+0

好的,让我试试这个。 – 2012-01-30 19:31:51

+0

@TCC:Dictionary是像你这样的问题的解决方案。 – 2012-01-30 19:43:57

+0

@TCC:发生了什么事? – 2012-01-31 18:39:55

2

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

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

+0

任何关于如何删除然后用我的代码实现的例子? – 2012-01-30 18:38:24