2012-01-30 19 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