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;
}
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With