我正在使用LINQ查询一个通用字典,并将结果作为我的ListView(WebForms)的数据源。
简化后的代码:
Dictionary<Guid, Record> dict = GetAllRecords();
myListView.DataSource = dict.Values.Where(rec => rec.Name == "foo");
myListView.DataBind();
我原本以为这样可以工作,但实际上它会抛出一个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();
第一个示例中是否存在小问题需要解决才能使其正常工作?
(对于这个问题的标题我不确定该使用什么,可以自由编辑为更合适的内容)