Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basic LINQ expression for an ItemCollection

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?

like image 755
sourcenouveau Avatar asked Jul 21 '09 18:07

sourcenouveau


People also ask

How do I select a query in LINQ?

LINQ query syntax always ends with a Select or Group clause. The Select clause is used to shape the data. You can select the whole object as it is or only some properties of it. In the above example, we selected the each resulted string elements.

What is LINQ in C# with example?

Language-Integrated Query (LINQ) is the name for a set of technologies based on the integration of query capabilities directly into the C# language. Traditionally, queries against data are expressed as simple strings without type checking at compile time or IntelliSense support.

What is LINQ to object?

The term "LINQ to Objects" refers to the use of LINQ queries with any IEnumerable or IEnumerable<T> collection directly, without the use of an intermediate LINQ provider or API such as LINQ to SQL or LINQ to XML. You can use LINQ to query any enumerable collections such as List<T>, Array, or Dictionary<TKey,TValue>.


1 Answers

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.

like image 70
Jon Skeet Avatar answered Sep 19 '22 16:09

Jon Skeet