我正在使用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();
在第一个例子中有没有让它工作的小陷阱?
(不确定使用什么作为这个问题的标题,请随意编辑为更合适的标题)
发布于 2008-08-28 05:23:15
试试这个:
var matches = dict.Values.Where(rec => rec.Name == "foo").ToList();
请注意,这实际上是从原始值集合创建一个新列表,因此对字典的任何更改都不会自动反映在绑定的控件中。
发布于 2008-08-28 11:22:22
我倾向于使用新的Linq语法:
myListView.DataSource = (
from rec in GetAllRecords().Values
where rec.Name == "foo"
select rec ).ToList();
myListView.DataBind();
你不用钥匙的时候为什么还要买字典?你要为这些开销买单。
发布于 2008-08-28 06:21:45
您也可以尝试:
var matches = new List<Record>(dict.Values.Where(rec => rec.Name == "foo"));
基本上,泛型集合很难直接转换,因此除了创建一个新对象之外,您几乎别无选择。
https://stackoverflow.com/questions/31708
复制相似问题