How can I add OrderBy to this LINQ statement?
Solution 1
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);
Solution 2
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.
Angry Dan
web/software developer, .NET, C#, WPF, PHP, software trainer, English teacher, have philosophy degree, love languages, run marathons my tweets: http://www.twitter.com/edward_tanguay my runs: http://www.tanguay.info/run my code: http://www.tanguay.info/web my publications: PHP 5.3 training video (8 hours, video2brain) my projects: http://www.tanguay.info
Updated on June 14, 2022Comments
-
Angry Dan over 1 year
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; }