Saturday, November 27, 2010

Dynamic LINQ to XML : Solving the OrderBy

With every new inovation lies new problems.  If you haven't checked out the awesome Dynamic library for LINQ to whatever,  you should.  The GU has a great post about it here.  I started using this and it worked great for LINQ to SQL, which is what I was using it for at the time.  Later I decided that I wanted to do some complex paging and sorting with a result set that was returning an XML document.  Based upon what I read in Scott's post it seemed like it supported LINQ to XML.  Well it sorta didn't.  You have to modify the Dynamic.cs file in order to get this to work.

The code that I was trying to execute looked something like this:


Click for larger image

This is the XML




The problem is that without any changes to the DynamicLibrary you get some error that either the Element is not a method of your object or your orderby selection is not a valid property. Ultimately it means that LINQ to XML doesn't support this right out of the box. Now I read another post that stated that the problem was that a few Objects were not in the predefinedTypes and so that got me thinking and I modified the Dynamic.vb file in my project...thats right V freakin B. I am sure the changes are quite similar in the Dynamic.cs file if you are programming in C#, but I was programming in VB.

Change your predefinedTypes to look like this and recompile and you should be able to do dynamic OrderBy with LINQ to XML:



 

No comments:

Post a Comment