为什么这个Linq查询字典< TKey,TValue>作为DataSource工作 [英] Why isn't this Linq query on Dictionary<TKey, TValue> working as DataSource
问题描述
我在VB中有以下内容:
I have the following in VB:
Dim sources = From source In importSources Select New With _
{.Type = source.Key, .Source = source.Value.Name}
dgridSourceFiles.DataSource = sources
当我调试时,来源
显示一个内存中查询,并有2条记录。但是datagrid视图不会显示记录。
When I debug, sources
shows an in-memory query and has 2 records within. Yet the datagrid view will not show the records.
为什么这不行?建议可以是VB或C#...
So why won't this work? suggestions can be either VB or C#...
当我使用:
Dim sources = (From source In importSources Select New With _
{.Type = source.Key, .Source = source.Value.Name}).ToList()
...显示数据源
推荐答案
您的LINQ查询被懒惰地评估,并且仅实现 IEnumerable< T>
接口(据我所知),这意味着在枚举器调用 MoveNext
在某处(例如在 foreach
循环中发生)。
Your LINQ query is lazily evaluated and implements the IEnumerable<T>
interface only (as far as I know), which means its results are not established until an enumerator calls MoveNext
somewhere (as happens within a foreach
loop, for example).
似乎 DataSource
属性不会以这种方式枚举其内容。完全希望执行 IList
(或其他几个接口之一,见下文),以便它可以通过索引访问项目。这是由控件内部用于排序,过滤等。考虑到这一点,很可能所有设置 DataSource
属性是检查对象的类型以查看是否实现任何支持的接口。所以我不认为 DataSource
属性是设计来处理这种类型的对象(一个懒惰的评估查询)。
It seems the DataSource
property does not enumerate its contents in this way. It's completely expecting an implementation of IList
(or one of a few other interfaces—see below) so that it can access items by index. This is used internally by the control for sorting, filtering, etc. With this in mind, it's likely that all setting the DataSource
property does is check the object's type to see whether it implements any of the supported interfaces. So I don't think the DataSource
property is designed to deal with this type of object (a lazily evaluated query) at all.
现在, ToList
调用用查询结果填充列表< T>
这个 实现 IList
,因此可以用作 DataSource
。
Now, that ToList
call populates a List<T>
with the results of your query; this does implement IList
and can therefore be used as the DataSource
.
我的理解是, DataSource
的原因只是作为对象
键入它希望以下接口的任何:
My understanding is that the reason DataSource
is typed merely as object
is that it expects any of the following interfaces:
-
IList
-
IListSource
(在这种情况下IListSource.GetList
方法与DataMember
属性一起使用以向控件提供数据) -
IBindingList
(将列表中的更改传播给UI更新的控件) -
IBindingListView
(如BindingSource
)
IList
IListSource
(in which case theIListSource.GetList
method is used together with theDataMember
property to provide data to the control)IBindingList
(which propagates changes in the list to the control for UI updates)IBindingListView
(likeBindingSource
)
是根据 MSDN文档。
这篇关于为什么这个Linq查询字典< TKey,TValue>作为DataSource工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!