views:

911

answers:

2

I'm getting data out of an XML file by sending a where clause as delegate to a custom method:

foreach (PageItem pageItem in GetPageItems(xmlDoc, sf => (int)sf.Element("id") == id))
{
    _collection.Add(pageItem);
}

which works fine but now I want to add an OrderBy clause as well, but can't get the right syntax, here it doesn't recognize "pageItem" in the OrderBy clause, etc.

How can I get OrderBy to work in code below?

public IEnumerable<PageItem> GetPageItems(XDocument xmlDoc, Func<XElement, bool> whereClause)
{
    var pageItems = xmlDoc.Descendants("pageItem")
        .Where(whereClause)
        .OrderBy((int)pageItem.Element("displayOrder").Value)
        .Select(pageItem => new PageItem
        {
            Id = (int)pageItem.Element("id"),
            WhenCreated = (DateTime)pageItem.Element("whenCreated"),
            ItemOwner = pageItem.Element("itemOwner").Value,
            PublishStatus = pageItem.Element("publishStatus").Value,
            CorrectionOfId = (int)pageItem.Element("correctionOfId"),

            IdCode = pageItem.Element("idCode").Value,
            Menu = pageItem.Element("menu").Value,
            Title = pageItem.Element("title").Value,
            Description = pageItem.Element("description").Value,
            AccessGroups = pageItem.Element("accessGroups").Value,
            DisplayOrder = (int)pageItem.Element("displayOrder")


        });
    return pageItems;
}
+3  A: 

I suspect you may want to change the line to be:

.OrderBy( p => (int)p.Element("displayOrder").Value )

The OrderBy() extension expects a "key selector" delegate (Func) which can be used to extract a key from the items you wish to order.

LBushkin
perfect, had to change it to this, but it worked: .OrderBy(p => Int32.Parse(p.Element("displayOrder").Value))
Edward Tanguay
It should work to cut out the .Value instead of modifying it to use Int32.Parse.
Ryan Versaw
+5  A: 

have you tried moving the OrderBy to AFTER the Select and using your PageItem object's property to order instead of the XML element?

// Move this to after the select...
.OrderBy(pi => pi.DisplayOrder);
Scott Ivey
that works too, I chose this as answer since it is terser, thanks!
Edward Tanguay