【问题标题】:Is LINQ to XML order dependent and can you number results with it?LINQ to XML 是否依赖于顺序,您可以用它对结果进行编号吗?
【发布时间】:2011-02-02 15:15:21
【问题描述】:

那么,我的第一个问题是,LINQ to XML 是否依赖于订单?

给定 XML(实际文件的简化版本):

<root>
    <dl Id='111' Or='true' />
    <dl Id='112' Or='false' />
</root>

容器:

public class root
{
    public int Position { get; set; }
    public int Id { get; set; }
    public bool Or { get; set; }
}

阅读器代码:

var t = a.DescendantsAndSelf("root").Descendants("dl").Select(b => new root
{
    Id = int.Parse(b.Attribute("Id").Value),
    Or = bool.Parse(b.Attribute("Or").Value)
});

t 中的根元素是否总是按照它们从文件中读取的顺序排列?如果没有,有没有办法强制排序?

第二个问题,有没有办法自动在阅读器代码中添加一个数字,说明它是第一个、第二个、第三个等要从 XML 中读出的根?所以在这个例子中,t 将包含两个具有值的元素

  1. dl.Position = 1,dl.Id = 111,dl.Or = true
  2. dl.Position = 2,dl.Id = 112,dl.Or = 假

【问题讨论】:

    标签: c# linq lambda linq-to-xml


    【解决方案1】:

    是的,LINQ 是“顺序依赖的”。您的对象是按照它们在 XML 文件中出现的顺序创建的。

    要获取位置,请使用包含索引的Select 版本:

    var t = a.DescendantsAndSelf("root").Descendants("dl").Select((b,idx) => new root
    {
        Id = int.Parse(b.Attribute("Id").Value),
        Or = bool.Parse(b.Attribute("Or").Value),
        Position = idx+1
    });
    

    【讨论】:

    • 非常感谢,没想到给LINQ加索引这么简单
    • 我也没有,直到有人在 SO 上向我解释它;)
    猜你喜欢
    • 2020-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-22
    • 1970-01-01
    相关资源
    最近更新 更多