score:92

Accepted answer

no, ienumerable doesn't have many extension methods on it: ienumerable<t> does. they are two separate interfaces, although ienumerable<t> extends ienumerable.

the normal linq ways of converting are to use the cast<t>() and oftype<t>() extension methods which do extend the nongeneric interface:

ienumerable<textbox> textboxes = controls.oftype<textbox>();
ienumerable<control> controls = controls.cast<control>();

the difference between the two is that oftype will just skip any items which aren't of the required type; cast will throw an exception instead.

once you've got references to the generic ienumerable<t> type, all the rest of the linq methods are available.

score:2

linq utilized generic collections. controlscollection implements ienumerable not ienumberable<t>

if you notice this will not work

((ienumerable)page.controls).where(...

however, this does

((ienumerable<control>)page.controls).where(...

you can either cast to generic ienumerable<t> or access an extension method that does, like so:

 page.controls.oftype<control>().where(c => c.id == "some id").firstordefault();

score:5

in addition to the answers provided by jon skeet and dan tao, you can use query expression syntax by explicitly providing the type.

control mycontrol = (from control control in this.controls
                    where control.id == "some id"
                    select control).singleordefault();

score:11

this is just because the controlcollection class came around before generics; so it implements ienumerable but not ienumerable<control>.

fortunately, there does exist a linq extension method on the ienumerable interface that allows you to generate an ienumerable<t> through casting: cast<t>. which means you can always just do this:

var c = controls.cast<control>().where(x => x.id == "some id").singleordefault();

Related Query

More Query from same tag