views:

111

answers:

3

I've been using LINQ for awhile (and enjoy it), but it feels like I hit a speedbump when I run across .NET specialized collections(DataRowCollection, ControlCollection). Is there a way to use LINQ with these specialized controls, and if not do you think Microsoft will address this in the next release of the framework? Or are we left to iterate over these the non-LINQ way, or pull the items out of the collection into LINQ-able collections ourselves?

+13  A: 

The reason why collections like ControlCollection do not work with LINQ is that they are not strongly typed. Without an element type LINQ cannot create strongly typed methods. As long as you know the type you can use the Cast method to create a strongly typed enumeration and hence be used with LINQ. For example

ControlCollection col = ...
var query = col.Cast<Control>().Where(x => ...);

As to will Microsoft ever make these implement IEnumerable<T> by default. My guess is no here. The reason why is that doing so is a breaking change and can cause expected behavior in code. Even simply implementing IEnumerable<Control> for ControlCollection would cause changes to overload resolution that can, and almost certainly will, break user applications.

JaredPar
That's the answer. Forgot about cast. Microsoft could still add Strongly Type Collections for ControlCollection and such. Thank you and thanks to all who contributed.
Bless Yahu
+1  A: 

The reason for this is: Collections which do not implement IEnumerable<T> or IQueryable, can not be iterated in LINQ

Asad Butt
has to be IEnumerable<T>
Paul Creasey
Well, all collections does implement IEnumerable (otherwise you would not be able to loop over them). But to be able to be used by linq they will have to implement the generic version (IEnumerable<T>).
Mattias Jakobsson
I mentioned Generic version of IEnumerable, but SOF(Text Editor) will not Let me do it. Did not notice it early, have made the correction. Thanks any way
Asad Butt
+3  A: 

You should be able to do something like this:

myDataRowCollection.Cast<DataRow>().Where.....

and use Linq that way. If you know what the objects in the collection are, then you should be able to use that.

BFree