Tuesday, 16 October 2012

Use generic linq extensions on non-generic collections

I was using an old (non-generic) .net collection called ChannelEndpointElementCollection to find a specified endpoint from web.config and then to pull out the details for one of them. I only had one initially so I just used mycollection[0] but then I added another endpoint and decided I didn't want to require the correct order of elements in order for this to remain working, I needed something like collection.First(p => p.Contract == "Contract1") which is when I realised that the generic extension methods like First, Select etc. do not work on non-generic collections because they cannot infer the type from the collection.
Fortunately, this was known by the powers-that-be who have added another extension method OfType<T>() which allows you to specify the type of the collection and therefore return a typed generic collection which can then be used with the other Linq extension methods:


var theAddress = endpointCollection.OfType<ChannelEndpointElement>().FirstOrDefault(p => p.Contract == "Contract1").Address;
Post a Comment