6

(Using the latest MVC 2 RC 2) I'm trying to sort some XML in LINQ (C#) by an element's attribute's value...

var sites = from s in xDoc.Element("sites").Elements("site")
orderby s.Attribute("name")
select s;

But when I pass this to my View I get the exception:

Exception Details: System.ArgumentException: At least one object must implement IComparable.
Source Error: 
Line 37:                </th>
Line 38:            </tr>
Line 39:            <% foreach (var item in Model)
Line 40:               { %>
Line 41:            <tr>

Can someone tell me how to sort XML using LINQ and have it render properly?

tereško
  • 58,060
  • 25
  • 98
  • 150
Matt W
  • 11,753
  • 25
  • 118
  • 215

1 Answers1

12

EDIT: Okay, I think you just want:

var sites = from s in xDoc.Element("sites").Elements("site")
            orderby (string) s.Attribute("name")
            select s;

Which could also be written as:

var sites = xDoc.Element("sites")
                .Elements("site")
                .OrderBy(s => (string) s.Attribute("name"));
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Sorry, yes, you're correct- I had copied the wrong piece of code into my post! Argh. I've corrected it now. – Matt W Feb 05 '10 at 17:14
  • The 'site' variable is the value I'm passing into my view, eg: return View(site); – Matt W Feb 05 '10 at 17:15
  • 2
    You may want to replace orderby (string) s.Attribute("name") by orderby s.Attribute("name").Value – Vitali Climenco May 06 '15 at 07:59
  • 1
    @VitaliClimenco: That depends on what you want to happen if the element doesn't have a `name` attribute. Using `.Value` it will throw an exception; using the cast it will just be ordered at the start (as nulls are). – Jon Skeet May 06 '15 at 08:15