Home > .net 3.5, c#, LINQ, Microsoft, Visual Studio 2008 > From the Forums – Casting XML Elements in LINQ-to-XML

From the Forums – Casting XML Elements in LINQ-to-XML

March 13, 2008

There was a post earlier today on the Microsoft asp.net forums of a user receiving a common error in LINQ-to-XML:

“At least one object must implement IComparable”

The LINQ query they were using was correct, except missing a very important bit of casting:

var allPersonsInOrderOfAge =
   from person in myXml.Descendants(“person”)
   orderby person.Element(“age”)
   select person;

We know that using the ‘where’ clause requires explicit casting when comparing against XML elements. 

However, the ‘orderby’ clause works the same way—if the compiler unsure of the type, it can’t compare them and thus cannot order them.  The error message thrown is correct at the compiler level, but totally useless to a developer.

To fix this, simply cast (bolded and larger below):

var allPersonsInOrderOfAge =

from person in myXml.Descendants(“person”)

       where (int)person.Element(“age”) >= 32

       orderby (int)person.Element(“age”) descending

       select person;

Or, for those interested, the Lambda expression version:

var allPersonsInOrderOfAgeLambda =

myXml.Descendants(“person”)

             .Where(x => (int)x.Element(“age”) >= 32)

             .OrderByDescending(x => (int)x.Element(“age”));

Now that the LINQ compiler knows that age is an integer, it can order it accordingly.

 

  1. Just3Ws
    July 31, 2008 at 7:21 am

    Thanks, this just saved me allot of time!

  2. Tank3
    July 31, 2008 at 12:03 pm

    Hey thanks! With this little snippet and the one I got from I will be rocking in no time! thanks again!

  3. almighty
    September 30, 2008 at 8:08 am

    It’s really save my more time and give one minute solution for the above error
    Thanks,

  1. No trackbacks yet.
Comments are closed.
%d bloggers like this: