Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/fortran/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 我可以使用LINQ在表单中获得所有类型的控件吗?_C#_Winforms_Linq - Fatal编程技术网

C# 我可以使用LINQ在表单中获得所有类型的控件吗?

C# 我可以使用LINQ在表单中获得所有类型的控件吗?,c#,winforms,linq,C#,Winforms,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()); } 它不起作用了( 编辑: 错误

我希望在列表框中显示表单中可用的所有类型的控件(无重复项)

我试过这个:

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());
}
它不起作用了(

编辑:

错误:找不到查询模式的实现
用于源类型“System.Windows.Forms.Control.ControlCollection”。

“选择”未找到。考虑显式指定范围变量的类型< /COD> < /P> > P>,您需要这样写< /P>
var controls=from Control control in this.Controls
                    select control;

希望这能起作用

对于这项任务来说,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);
foreach(this.Controls.OfType()中的var typeName.Select(c=>c.GetType().ToString()).Distinct())
listBox1.Items.Add(typeName);

编辑:为了得到与您现在得到的完全相同的结果,不要使用
.GetType()
。直接在控件上调用
.ToString()
。但是,您的问题是“控件类型”,所以我不确定您的目标是什么。

我已经成功了!没有重复项,我只是添加了
控件。GetType().ToString()

使用以下命令:

var controls=from Control control in this.Controls.OfType<Control>()
             select control;
var controls=来自this.controls.OfType()中的控件
选择控件;

这样会更好,不是吗

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

什么不起作用?这里有错误吗?这里:<代码>找不到源类型“Stasy.Windows。窗体。控件。控件集合”。“未选择”的查询模式的实现。请考虑显式指定范围变量< /代码>的类型(从该控件中的“控件”,“控件”选择“TestCube”)。;似乎两个按钮是不同的,因为它们具有唯一的
Text
属性。所以基本上
distinct()
并不能解决问题……为什么我不能在这个linq语句中添加位置?@Ian Henry:只是探索linq:)我使用了你的第一个解决方案,这很好,但我仍然可以为同一个控件获得重复项。。。。你的第二个解决方案抛出了一个与我发布的相同的错误。对,这是有意义的。。。我用显式类型声明对其进行了编辑,这应该可以解决这个问题;我的错。再次编辑,这次实际测试。似乎
ControlCollection
实现了
IEnumerable
,而不是
IEnumerable
…最不令人惊讶的原则,有人吗?我想我必须在这里问一下,以便找到解决方案:)
var controls = (from Control control in this.Controls 
               select control.GetType().ToString()).Distinct();
this.listBox2.Items.AddRange(controls.ToArray());