ItemCollection的基本LINQ表达式 [英] Basic LINQ expression for an ItemCollection

查看:135
本文介绍了ItemCollection的基本LINQ表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 ItemCollection 我想使用LINQ查询.我尝试了以下(人为)示例:

I have an ItemCollection that I'd like to query using LINQ. I tried the following (contrived) example:

var lItem =
    from item in lListBox.Items
    where String.Compare(item.ToString(), "abc") == true
    select item;

Visual Studio不断告诉我Cannot find an implementation of the query pattern for source type 'System.Windows.Controls.ItemCollection'. 'Where' not found. Consider explicitly specifying the type of the range variable 'item'.

Visual Studio keeps telling me Cannot find an implementation of the query pattern for source type 'System.Windows.Controls.ItemCollection'. 'Where' not found. Consider explicitly specifying the type of the range variable 'item'.

如何解决该问题?

推荐答案

这是因为ItemCollection仅实现IEnumerable,而不实现IEnumerable<T>.

It's because ItemCollection only implements IEnumerable, not IEnumerable<T>.

您需要有效地调用Cast<T>(),如果您明确指定范围变量的类型,则会发生这种情况:

You need to effectively call Cast<T>() which is what happens if you specify the type of the range variable explicitly:

var lItem = from object item in lListBox.Items
            where String.Compare(item.ToString(), "abc") == 0
            select item;

以点表示法是:

var lItem = lListBox.Items
                    .Cast<object>()
                    .Where(item => String.Compare(item.ToString(), "abc") == 0));

当然,如果您对集合中的内容有更好的了解,则可以指定比object更具限制性的类型.

If course, if you have a better idea of what's in the collection, you could specify a more restrictive type than object.

这篇关于ItemCollection的基本LINQ表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆