Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter controls by type and property value using C#

Tags:

c#

winforms

Is there efficient way to filter Panel's child controls by their type e.g. Label property e.g. Tag value?

E.g. I have a panel1:

label1.Tag=1;
label2.Tag=1;
label3.Tag=2;
label4.Tag=3;
textBox1.Tag=1;
panel1.Add(controls above);

I would like to get all labels in the collection, or all the controls with Tag=1, or use and between the statements.

like image 433
insomnium_ Avatar asked Oct 17 '25 01:10

insomnium_


1 Answers

You can filter all controls of a specific type using the OfType extension method:

var labelControls = panel.Controls.OfType<Label>();

Then if you want to add additional filtering (e.g. based on the tag):

var filteredLabelControls = labelControls.Where(l => l.Tag == (object)1);
like image 111
Erik Schierboom Avatar answered Oct 18 '25 17:10

Erik Schierboom