Wednesday, October 10, 2007

LINQ to Controls

In a perfect world, we'd be able to do this on a form:

var disabled = Controls.Select( c => !c.Enabled );

However, the Controls collection isn't one that is natively supported by LINQ. MS developed the custom collection of ControlCollection rather than using a generic (since generics didn't exist at the time).

There's a way around the problem. Since the generics namespace adds the "Cast" extension method when it sees the "IEnumerable" interface, we can just cast the list objects as Control. Once you've done that, then you just do your normal LINQ queries.

var disabled = Controls.Cast<Control>().Select( c => !c.Enabled );

Or the more SQL-esque way:

var invalid = from cont in Controls.Cast<Control>()
where cont.Text == "" && cont.Visible
select cont;

No comments: