2009-10-06 119 views
2

我试图帮助别人了,写这个查询:为什么这个LINQ Query不工作?

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

而且他们报告说,他们收到此错误:

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

我查MSDN和TabPageCollection工具IListICollectionIEnumerable。那么,这里发生了什么?那个错误是什么意思,还有另一种方式来查询选项卡控件的TabPages属性?

回答

8

尝试这种情况:

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

此代码指定的范围内的变量的类型。此外

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

,请确保您有

using System.Linq; 

在你的文件的顶部:

+0

我总是忘记一个:) – leppie 2009-10-06 03:49:15

+0

看起来比cast方法更清洁。谢谢! – jasonh 2009-10-06 03:53:20

0

试试这个。

迪伦

4

TabPageCollection实现IEnumerable但不IEnumerable<T>这正是LINQ使用。要修复,请使用如下所示的投射方法:

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

除了我所犯的原始错误(“tab”两次,我忘记了select子句,我很惊讶没有人注意到,LOL!),这是完美的。感谢提到'IEnumerable''' IEnumerable '的解释。 – jasonh 2009-10-06 03:49:23

+0

错误:Aquery body必须以select或group子句结尾 – Anuya 2009-10-06 03:53:13

+0

呵呵!复制粘贴错误:P – 2009-10-06 03:56:25

2

但是,但是......?如果你有这个名字,你可以直接引用它? TabPages [“tabname”]

+0

嘘!如果你不使用LINQ,你只是不编程... – Massif 2012-03-08 16:27:08

+0

我已经编程了20年,在你脱离尿布之前做过LINQ。曾在微软的Premier .NET团队工作过。嘘你自己傻瓜! (笑) - 如果你曾经忍受过微软的采访,他们会嚷嚷你使用LINQ(我爱)的开销,而不是仅仅索引到页面索引器。 – 2012-03-12 14:38:01