我只想問:這是一個方法體中的多鍵詞典的高效代碼嗎?
- 下面的代碼是有效的嗎?
- 有沒有更好的方法來處理這個問題?
- 如何編碼是否需要表名/字段名對的附加值?
我們需要使用包含諸如(TableName,FieldName,FieldValue)之類的多鍵字典。
我搜索了一些答案,但我發現迄今爲止不適用於我們的設置。我們使用3.5,所以沒有可用的Tuple。我們還將此腳本邏輯與只允許在方法體內進行編碼的應用程序集成,因此我們受到限制,無法創建單獨的類/結構等。我們的設置是C#/ VS 2010.
任何幫助表示讚賞。提前致謝!
Dictionary<string, Dictionary<string, string>> tableList = new Dictionary<string, Dictionary<string, string>>();
Dictionary<string, string> fieldList = new Dictionary<string, string>();
// add fields to field list, then add the field lists to the corresponding table list
// clear field list for next table
// values are just hardcoded here to simplify, but is being read from actual objects in the application
fieldList.Add("Field1", "abc");
fieldList.Add("Field2", "def");
fieldList.Add("Field3", "ghi");
fieldList.Add("Field4", "jkl");
tableList.Add("Table1", new Dictionary<string, string>(fieldList));
fieldList.Clear();
fieldList.Add("Field1", "xyz");
fieldList.Add("Field2", "uvw");
fieldList.Add("Field3", "rst");
tableList.Add("Table2", new Dictionary<string, string>(fieldList));
fieldList.Clear();
fieldList.Add("Field1", "123");
fieldList.Add("Field2", "456");
tableList.Add("Table3", new Dictionary<string, string>(fieldList));
fieldList.Clear();
// Display tables and corresponding fields
foreach (KeyValuePair<string, Dictionary<string, string>> fieldList4 in tableList)
{
foreach (KeyValuePair<string, string> fieldList5 in fieldList4.Value)
{
txtMessage.Text = txtMessage.Text + "\r\nTable=" + fieldList4.Key + ", Field=" + fieldList5.Key + " - " + fieldList5.Value;
}
}
// Try to find tables and fields in the lists, and list the value if found
string tableToFind = "Table2";
string fieldToFind = "Field2";
Dictionary<string, string> tableFields = new Dictionary<string, string>();
if (tableList.Keys.Contains(tableToFind) == true)
{
txtMessage.Text = txtMessage.Text = "\r\nTable=" + tableToFind + " exist in table list";
tableList.TryGetValue(tableToFind, out tableFields);
if (tableFields.Keys.Contains(fieldToFind) == true)
{
foreach(KeyValuePair<string, string> fieldData in tableFields)
{
if (fieldData.Key == fieldToFind)
{
txtMessage.Text = txtMessage.Text + "\r\nTable=" + tableToFind + ", Field=" + fieldData.Key +
" with value=" + fieldData.Value + " exist in table list";
break;
}
}
}
}
爲什麼不利用Sugar提供的一些有用的語法? – ChaosPandion
使用單個字典完成此操作的一種方法是將表鍵和字段鍵合併成一個字符串,例如。 「表1 |字段1」。不知道這是否更有效。 –
如果您對弱類型數據集語義有要求,是否有任何理由不使用這些類?如果可能的話,我認爲最好的做法是使用強類型的解決方案。 –