基本的LINQexpression式为一个ItemCollection

我有一个我想用LINQ查询的ItemCollection 。 我尝试了以下(做作)的例子:

 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'. 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>

您需要有效地调用Cast<T>() ,这是如果明确指定范围variables的types会发生什么情况:

 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更具限制性的types。

您需要指定“项目”的types

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