我使用LINQ查询泛型字典,然后使用结果作为我的ListView(WebForms)的数据源.
简化代码:
Dictionarydict = GetAllRecords(); myListView.DataSource = dict.Values.Where(rec => rec.Name == "foo"); myListView.DataBind();
我认为这会工作,但实际上它会抛出一个System.InvalidOperationException:
ID为'myListView'的ListView必须具有实现ICollection的数据源,或者如果AllowPaging为true,则可以执行数据源分页.
为了使它工作,我不得不采取以下措施:
Dictionarydict = GetAllRecords(); List searchResults = new List (); var matches = dict.Values.Where(rec => rec.Name == "foo"); foreach (Record rec in matches) searchResults.Add(rec); myListView.DataSource = searchResults; myListView.DataBind();
在第一个例子中是否有一个小问题使它工作?
(不知道该使用什么作为这个问题的标题,随意编辑更合适的东西)
试试这个:
var matches = dict.Values.Where(rec => rec.Name == "foo").ToList();
请注意,这实际上将从原始值集合中创建新列表,因此对字典的任何更改都不会自动反映在绑定控件中.
我倾向于使用新的Linq语法:
myListView.DataSource = ( from rec in GetAllRecords().Values where rec.Name == "foo" select rec ).ToList(); myListView.DataBind();
当你不使用密钥时,为什么要收到字典?你付出了这笔费用.