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?
You can use LINQ to query any enumerable collections such as List<T>, Array, or Dictionary<TKey,TValue>. The collection may be user-defined or may be returned by a . NET API.
Compared to SQL, LINQ is simpler, tidier, and higher-level. It's rather like comparing C# to C++. Sure, there are times when it's still best to use C++ (as is the case with SQL), but in most situations, working in a modern tidy language and not having to worry about lower-level details is a big win.
Readable code: LINQ makes the code more readable so other developers can easily understand and maintain it. Standardized way of querying multiple data sources: The same LINQ syntax can be used to query multiple data sources. Compile time safety of queries: It provides type checking of objects at compile time.
It is slightly slower It's good to be aware of any performance tradeoff that might occur when you use LINQ to improve the readability of your code. And if you'd like to measure the performance difference, you can use a tool like BenchmarkDotNet to do so.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With