如何将OrderBy添加到此LINQ语句中?

时间:2021-10-23 06:50:55

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

我通过将where子句作为委托发送到自定义方法来从XML文件中获取数据:

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.

哪个工作正常,但现在我想添加一个OrderBy子句,但无法获得正确的语法,这里它不识别OrderBy子句中的“pageItem”等。

How can I get OrderBy to work in code below?

如何让OrderBy在下面的代码中工作?

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;
}

2 个解决方案

#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?

您是否尝试将OrderBy移动到选择后并使用PageItem对象的属性来命令而不是XML元素?

// Move this to after the select...
.OrderBy(pi => pi.DisplayOrder);

#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.

OrderBy()扩展需要一个“键选择器”委托(Func),它可用于从您要订购的项目中提取密钥。

#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?

您是否尝试将OrderBy移动到选择后并使用PageItem对象的属性来命令而不是XML元素?

// Move this to after the select...
.OrderBy(pi => pi.DisplayOrder);

#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.

OrderBy()扩展需要一个“键选择器”委托(Func),它可用于从您要订购的项目中提取密钥。