我使用LINQ查询泛型字典,然后使用结果作为我的ListView(WebForms)的数据源.
简化代码:
Dictionary<Guid, Record> dict = GetAllRecords();
myListView.DataSource = dict.Values.Where(rec => rec.Name == "foo");
myListView.DataBind();
Run Code Online (Sandbox Code Playgroud)
我认为这会工作,但实际上它会抛出一个System.InvalidOperationException:
ID为'myListView'的ListView必须具有实现ICollection的数据源,或者如果AllowPaging为true,则可以执行数据源分页.
为了使它工作,我不得不采取以下措施:
Dictionary<Guid, Record> dict = GetAllRecords();
List<Record> searchResults = new List<Record>();
var matches = dict.Values.Where(rec => rec.Name == "foo");
foreach (Record rec in matches)
searchResults.Add(rec);
myListView.DataSource = searchResults;
myListView.DataBind();
Run Code Online (Sandbox Code Playgroud)
在第一个例子中是否有一个小问题使它工作?
(不知道该使用什么作为这个问题的标题,随意编辑更合适的东西)