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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1069426/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 07:29:56  来源:igfitidea点击:

How can I add OrderBy to this LINQ statement?

c#linqlinq-to-xml

提问by Edward Tanguay

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

采纳答案by Scott Ivey

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 移动到 Select 之后并使用您的 PageItem 对象的属性来排序而不是 XML 元素?

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

回答by LBushkin

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),它可用于从您希望订购的项目中提取键。