c# - Iterate over Database table row and store values in a Dictionary? -
i want implement dictionary cache in program. how can store database result seen in image below in dictionary collection ?
i want iterate on database table , store content of languagename , isocode columns in dictionary dictionary<languagename,isocode>
.
my database (ctlang) looks this:
here code:
private string getlanguageforisocode(string isocode) { //check isocode column , return corresponding language using (var unitofwork = dataaccessunitofworkfactory.create()) { //need call every time sql query string query = "select languagename ctlang isocode='" + isocode + "'"; list<string> result = unitofwork.owentities.database.sqlquery<string>(query).tolist(); if (result.firstordefault() != null) { return result.firstordefault(); } //if language not available in database, fallback german default language thread.currentthread.currentculture = cultureinfo.getcultureinfo("de"); //displayname = deutsch return cultureinfo.getcultureinfo("de").nativename; } }
bonus question: how can search key in dictionary using value ?
it is. there no problem in returning key value, issue there theoretically more 1 key assigned value, since key matters. in particular case should no problem, since 1 isocode represents 1 language. there no problem make that, dictionary:
public dictionary<string, string> languagesandkeys = new dictionary<string, string>(); //create
then can search keys/values that:
string myvaluebykey = languagesandkeys["mykey"]; //getting value key easy string mykeybyvalue = languagesandkeys.firstordefault(item => item.value == "myvalue").key; //getting key of first matching value/or returning default type. you'll need check sure.
afterwards, can load data sql table dictionary. goal, can either use temporary datatable dataadapter, work long table not big, or can use datareader loop trough rows in sql table 1 one. i'm gonna using temp datatable:
string cmdtext = "select * ctlang"; //as far saw cmd text in code example, may still want take tho string connectionstring = ""; //fill connection string according sql server data sqldataadapter dataadapter = new sqldataadapter(cmdtext, connectionstring); datatable dtable = new datatable(); dataadapter.fill(dtable); foreach(datarow row in dtable.rows) languagesandkeys.add(row[1].tostring(), row[0].tostring());//second column key, first column value - structure of table.
Comments
Post a Comment