I was working on an implementation of a REST service recently, making it respond to the HTTP Accept headers on the incoming request. As you can see from the HTTP/1.1 specification, Accept request-headers should be honored in the order that they’re listed. So it was absolutely awesome to learn that
using System.ServiceModel.Web; var acceptHeaders = WebOperationContext.Current.IncomingRequest.GetAcceptHeaderElements(); foreach ( var acceptHeader in acceptHeaders ) { // process acceptHeader... }
processes the headers in the opposite order in which they are specified in the request. And that’s not awesome in a good sense.
The IncomingWebRequestContext.GetAcceptHeaderElements method returns a System.Collections.ObjectModel.Collection<T> and that is not a class I own or can change. But still I’d like an iterator for Collection<T> that yields up its elements in reverse order so that I can still use the foreach syntax. Since Collection<T> is not a class I can modify, extension methods come to mind. Here’s an extension method for an iterator on Collection<T> that does the trick.
using System.Collections.Generic; using System.Collections.ObjectModel; public static class Extensions { public static IEnumerable<T> Reverse<T>( this Collection<T> collection ) { for ( int i = collection.Count - 1; i >= 0; --i ) yield return collection[ i ]; } }
Now I can write the foreach loop to use the extension method.
foreach ( var acceptHeader in acceptHeaders.Reverse() ) { // process acceptHeader in the correct order... }
I am still dumbfounded that GetAcceptHeaderElements reverses the order of the elements (why would that ever be good?) but a few lines sends me on my way without cluttering up the code.