2010-11-11 51 views
2

我想在列表框中显示所有类型的控件(不重复)。我可以使用LINQ来获取我的表单中的各种控件吗?

我尝试这样做:

var controls = from c in this.Controls 
       select c; 

foreach (var x in controls) 
{ 
    StringBuilder sb = new StringBuilder(); 
    sb.Append(x); 
    listBox1.Items.Add(sb.ToString()); 
} 

它不工作。 :(

编辑:

Error: Could not find an implementation of the query pattern for source type 'System.Windows.Forms.Control.ControlCollection'.
'Select' not found. Consider explicitly specifying the type of the range variable

+0

什么不工作?有没有错误? – RPM1984 2010-11-11 05:12:39

+0

here:'无法找到源类型'System.Windows.Forms.Control.ControlCollection'的查询模式的实现。 '选择'未找到。考虑明确指定范围变量的类型“ – yonan2236 2010-11-11 05:14:35

回答

3

LINQ是矫枉过正这个任务原来是使用StringBuilder。你可以简单地使用:

foreach (var x in this.Controls) 
    listBox1.Items.Add(x.GetType().ToString()); 

或为不同的类型名称:

foreach(var typeName in this.Controls.OfType<Control>().Select(c => c.GetType().ToString()).Distinct()) 
    listBox1.Items.Add(typeName); 

编辑:如你现在得到完全相同的结果,不要使用.GetType()。直接拨打.ToString()即可。不过,你的问题是“控制类型”,所以我不确定你的目标是什么。

+1

@Ian Henry:只是探索LINQ :) – yonan2236 2010-11-11 05:31:22

+0

我用你的第一个解决方案很好,但我仍然得到重复的相同的控制....你的第二个解决方案抛出一个错误,这是我发布的相同。 – yonan2236 2010-11-11 05:34:13

+0

对,这是有道理的...我用显式类型声明编辑它应该解决问题。 – 2010-11-11 05:36:33

4

你需要把它写这样

var controls=from Control control in this.Controls 
        select control; 

希望这将工作

+0

是的,它的工作原理!但是,我应该如何删除重复项? – yonan2236 2010-11-11 05:20:51

+1

(从this.Controls中的this thisControl选择thisControl).Distinct(); – mikel 2010-11-11 05:21:36

+0

@ yonan2236。什么@ miket2e说是正确的使用Distinct() – anishMarokey 2010-11-11 05:22:55

0

我明白了!没有重复,我只是说control.GetType().ToString()

var controls = (from Control control in this.Controls 
       select control.GetType().ToString()).Distinct(); 

foreach (var x in controls) 
{ 
    StringBuilder sb = new StringBuilder(); 
    sb.Append(x); 
    listBox2.Items.Add(sb.ToString()); 
} 
2

使用此:

var controls=from Control control in this.Controls.OfType<Control>() 
      select control; 
0

这会更好。不是吗?

var controls = (from Control control in this.Controls 
       select control.GetType().ToString()).Distinct(); 
this.listBox2.Items.AddRange(controls.ToArray()); 
相关问题