开发者

Is LINQ to XML order dependent and can you number results with it?

So, my first question, is LINQ to XML order dependent?

Given the XML (simplified version of the actual file):

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

The container:

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

The reader code:

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)
开发者_C百科});

Will the root elements in t always be in the order they were read out of the file? If not, is there any way to enforce ordering?

The second question, is there any way to automatically add a number to the reader code that says whether it was the first, second, third, etc. root to be read out of the XML? So in this example have it so t would contain two elements with the values

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


Yes, LINQ is "order dependent". Your objects get created in the order in which they appear in the XML file.

To get the position, use the version of Select which includes an index:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜