简体   繁体   中英

Why doesn't this LINQ Query Work?

I was attempting to help someone else out and wrote this query:

var foundTab = (from tab in tabControl1.TabPages
                where tab.Name == "tabName"
                select tab).First();

And they reported that they received this error:

Could not find an implementation of the query pattern for source type System.Windows.Forms.TabControl.TabPageCollection'. 'Where' not found. Consider explicitly specifying the type of the range variable 'tab'.

I checked MSDN and TabPageCollection implements IList , ICollection , IEnumerable . So, what's going on here? What does that error mean and is there another way to query the Tab Control's TabPages property?

Try this:

var tab = (from System.Windows.Forms.TabPage tab in tabControl1.TabPages
           where tab.Name == "tabName"
           select tab).First();

This code specifies the type of the range variable.

TabPageCollection implements IEnumerable but not IEnumerable<T> which is what LINQ uses. To fix, use the cast method like so:

var foundTab = (from tab in tabControl1.TabPages.Cast<TabPage>()
            where tab.Name == "tabName"
            select tab).First();

But, but but....? you could just reference it directly if you have the name? TabPages["tabname"]

Try this:

var tab = tabControl1.TabPages.FirstOrDefault(t => t.Name == "tabName");

Also, make sure you have

using System.Linq;

at the top of your file.

Dylan

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM