Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add OrderBy to this LINQ statement?

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;
}
like image 809
Edward Tanguay Avatar asked Dec 30 '22 20:12

Edward Tanguay


2 Answers

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);
like image 78
Scott Ivey Avatar answered Jan 01 '23 10:01

Scott Ivey


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.

like image 38
LBushkin Avatar answered Jan 01 '23 10:01

LBushkin