在winform应用程序中,通过BindingSource属性将Listbox与Dictionary绑定。
如何通过类型转换将此BindingSource恢复为原始字典?
例如:
Dictionary<string, string> objDic = getData();
OrderedDictionry ord = GetOrderedDict(objDic)
listBox.DataSource = new BindingSource(ord , null);
listBox.DisplayMember = "Value";
listBox.ValueMember = "Key";
现在,我希望来自listBox.DataSource
的相同字典类型值用于Linq查询!!。
例如:
var r = from t in (listBox.DataSource as Dictionary<string, string>).AsEnumaerable()
select t;
抛出错误?
如何输入强制转换为字典?
答案 0 :(得分:1)
编辑2 - 进一步讨论/检查后:
Dictionary<string, string> A = (from t in ((OrderedDictionary)(((BindingSource)listBox1.DataSource).DataSource)).Cast<KeyValuePair<string, string>>() select t).ToDictionary(d => d.Key, d => d.Value);
答案 1 :(得分:1)
您正在尝试将BindingSource转换为Dictionary。您需要转换BindingSource的 DataSource 。
我认为您不能 从OrderedDictionary
转换为Dictionary<>
,但重建Dictionary<string, string>:
BindingSource bs = (BindingSource)listBox1.DataSource;
OrderedDictionary ord = (OrderedDictionary)bs.DataSource;
Dictionary<string, string> dict = new Dictionary<string, string>();
foreach (DictionaryEntry item in ord)
dict.Add(item.Key.ToString(), item.Value.ToString());
如果你想要一个LINQ版本,你可以这样做:
BindingSource bs = (BindingSource)listBox1.DataSource;
OrderedDictionary ord = (OrderedDictionary)bs.DataSource;
var dict = ord.Cast<DictionaryEntry>().ToDictionary(d => d.Key, d => d.Value);