Search code examples
c#foreachoftype

OfType ForEach exclude particular elements


I have a line of code that clears all labels from the form

Controls.OfType<Label>().ToList().ForEach(p => p.Visible = false);

Now I need to exclude particular labels(either by id or text) from that list (like title labels). Is there a way to do so by modifying that line of code alone? I found out about Where(), though I am not sure about the syntax that goes inside those brackets.


Solution

  • I believe you want something like this:

    Controls.OfType<Label>().Where(lbl => lbl.Title != "something").ToList().ForEach(p => p.Visible = false);