views:

523

answers:

2

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

How do I fix the problem?

+12  A: 

It's because ItemCollection only implements IEnumerable, not IEnumerable<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;

In dot notation, this is:

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

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

Jon Skeet
Thanks! I also needed to cast the item (from object to its actual type) in the where clause, in order to access the property I was interested in.
emddudley
Don't cast in the where clause - just change the type argument to the Cast method!
Jon Skeet
+1  A: 

You need to specify the type of "item"

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