Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ to XML At least one object must implement IComparable

Tags:

xml

linq

I want to get the highest attribute "ID" from my XML file.

My code:

    var doc = XElement.Load("invoices.xml");

    var q = (from f in doc.Element("ListOfInvoices").Elements("Invoice")
             orderby f.Attributes("ID") descending
             select f.Attribute("ID")).FirstOrDefault();

When in my XML file is one of Invoice code works, but when is for example 2 invoice I have an error:

At least one object must implement IComparable.

like image 720
Never Avatar asked Feb 21 '23 11:02

Never


1 Answers

Try casting f.Attributes("ID") into an int if it's numeric or a string if it's alphanumeric like this:

var q = (from f in doc.Element("ListOfInvoices").Elements("Invoice")
             orderby (int)f.Attribute("ID") descending
             select f.Attribute("ID")).FirstOrDefault();
like image 75
Mithrandir Avatar answered Mar 24 '23 07:03

Mithrandir