LINQ to XML. At least one object must implement IComparable

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

My code is:

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 one of the invoice code works in my XML file, but when there are, for example, 2 invoices, I have an error:

At least one object must implement IComparable.

+4
source share
3 answers

Try distinguishing f.Attributes("ID") in int if it is numeric or string if it is alphanumeric:

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

You must explicitly access XAttribute.Value :

 doc.Element("ListOfInvoices") .Elements("Invoice") .Select(f => f.Attribute("ID").Value) .OrderByDecending(a => a).FirstOrDefault(); 
+1
source

There was a typo in the order. You write attributes instead of attribute.

To get the value of the attribute of the Value attribute, use the Value property:

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

Source: https://habr.com/ru/post/1396846/


All Articles