Introduction

I had some free time at last, so I implemented a LINQ extension to Flickr, so you can query for photos by tags, creation date, user id or title.

The implementation was really easy because I didn't have to use the Flickr APIs directly as I found a good open source library for this called FlickrNet which I used as my infrastructure. This is a sample of a query:

In the last example, I retrieved all the photos tagged with "silverkey".Note, you will need to create Flickr API AppKey, it is free. Just visit this page and register.

How To Implement This ?

The point is implementing the IQueryable<T> interface so you can plug your logic in LINQ automatically. Let's look at the PhotoQuery class:

publicclass PhotoQuery : IQueryable<FlickrPhoto>

This is the signature of the PhotoQuery class. It implements the IQueryable interface, which has two methods, CreateQuery, Execute, and because it implements IEnumerable<T>, you have to implement GetEnumerator(), and also IEnumerable and IQueryable are implemented implicitly in IQueryable<T>.

As you can see, we didn't implement all the functions. We just implemented IQueryable<T>.CreateQuery, IEnumerable.GetEnumerator. Basically the CreateQuery method just assigns the passed expression parameter to the MemberExpression and returns this cased as IQueryable. The parsing logic is in the IEnumerable.GetEnumerator, currently because this is just a prototype I implement where the ParseExpression method contains the parsing logic:

The important part is in the MethodCall function which parses expressions of type MethodCallExpression. Currently it handles the MemberAccess which is assigning values to properties, then it makes a switch on all the properties which can be used as a query condition like the Title, DateAdded, Tags, UserId, etc., and saves the value passed in the query in member variables declared in the PhotoQuery class itself. The last part which is executing this query is implemented in this function:

This function is called at the end of the IEnumerable<T>.GetEnumerator() after parsing the query expression. Here is where I use the FlickrNet library to search for photos from Flickr. Using the PhotoSearchOptions object, I assign the parsed query values stored in the member variables _tags, _title, _userId, etc., and then perform the search. The LINQ to Flickr code is attached with this post. Have fun.