2010-11-11 36 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()); 
相關問題