>DataSet ds = SomeMethodThatReturnsADataSet("MyDS"); >Dictionary<string,string> MyDictionary = new Dictionary<string,string>(StringComparer.CurrentCultureIgnoreCase); > >foreach(DataRow dr in ds.Tables[0].Rows) > MyDictionary.Add(dr["KeyName"].ToString(),dr["KeyValue"].ToString()); > >>
public IEnumerable<KeyValuePair<string,string>> GetEntries(DataTable dt, string keyField, string valueField) { foreach (DataRow d in dt.AsEnumerable()) { yield return new KeyValuePair<string, string>(d[keyField].ToString(), d[valueField].ToString()); } }which could then be called as:
foreach (var v in GetEntries(ds.Tables[0], "KeyName", "KeyValue")) { MyDictionary.Add(v.Key, v.Value); }Not much benefit there as is but if you ever needed to do things like selectively filtering the list it could be more useful. e.g:
var v2 = from x in GetEntries(dt,"KeyName","KeyValue").Where(x=>x.Value.StartsWith("Fred")) select x ; foreach( KeyValuePair<string,string> xx in v2) { MyDictionary.Add(xx.Key, xx.Value); }