开发者

Reorder using Join in Linq

开发者 https://www.devze.com 2023-02-15 00:29 出处:网络
I want my XElements in document order. Can I reorder my xpathGroups using Join like in this example? XDocument message_doc = XDocument.Load(message);

I want my XElements in document order. Can I reorder my xpathGroups using Join like in this example?

XDocument message_doc = XDocument.Load(message);

var xpathGroups =
    from e in contextErrors
    group e by SelectElement(message_doc, e.XPath) into g
    select new
    {
        Element = g.Key,
        ErrorItem开发者_运维百科s = g,
    };

var documentOrderedGroups =
    from elem in message_doc.Root.DescendantsAndSelf()
    join e in xpathGroups on elem equals e.Element
    select e;

Message:

<root>
    <a>
        <aa>
            <aaa>9999</aaa>
        </aa>
        <aa>
            <aaa>8888</aaa>
        </aa>
    </a>
    <b>
        <bb>
            <bbb>7777</bbb>
        </bb>
    </b>
    <c>
        <cc>
            <ccc>6666</ccc>
        </cc>
    </c>
</root>

Input data:

/root/c[1]/cc[1]/ccc[1]
/root/a[1]/aa[2]/aaa[1]
/root/b[1]/bb[1]/bbb[1]
/root/a[1]/aa[1]/aaa[1]

Expected result:

/root/a[1]/aa[1]/aaa[1]
/root/a[1]/aa[2]/aaa[1]
/root/b[1]/bb[1]/bbb[1]
/root/c[1]/cc[1]/ccc[1]


Your original queries work, and the result is an object with the element and its relevant XPath query in document order. However, the result conflicts with the comment you made that you only want the elements in document order.

Elements and XPath: if you want both the element and its XPath then the join will remain as part of the query but I would replace the grouping with a projection into an anonymous type.

var xpathElements = contextErrors.Select(e => new
                    {
                        Element = message_doc.XPathSelectElement(e.XPath),
                        XPath = e.XPath
                    });
var ordered =  from e in message_doc.Descendants()
               join o in xpathElements on e equals o.Element
               select o;

Elements only: if you only want the elements to be in document order, the following approach would work as well.

var xpathElements = contextErrors.Select(e => message_doc.XPathSelectElement(e.XPath));
var ordered = message_doc.Descendants()
                         .Where(e => xpathElements.Any(o => e == o));

In both examples I've used the XPathSelectElement method to take the place of your SelectElement method, which I gather has the same purpose.

0

精彩评论

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