使用LINQ to XML,如何根据序数位置连接两组数据? [英] Using LINQ to XML, how can I join two sets of data based on ordinal position?

查看:49
本文介绍了使用LINQ to XML,如何根据序数位置连接两组数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用LINQ to XML,如何根据序数位置连接两组数据?

Using LINQ to XML, how can I join two sets of data based on ordinal position?

<document>
    <set1>
        <value>A</value>
        <value>B</value>
        <value>C</value>
    </set1>
    <set2>
        <value>1</value>
        <value>2</value>
        <value>3</value>
    </set2>
</document>

基于上面的片段,我想将两个集合结合在一起,以使"A"和"1"在同一记录中,"B"和"2"在同一记录中,而"C"和"3"在同一记录中.

Based on the above fragment, I would like to join the two sets together such that "A" and "1" are in the same record, "B" and "2" are in the same record, and "C" and "3" are in the same record.

推荐答案

这是

This is what the Enumerable.Zip extension does in .NET 4. You'd write it like so (assuming that this is the entire XDocument):

var set1Elements = document.Element("set1").Elements();
var set2Elements = document.Element("set2").Elements();
var results = set1Elements.Zip(set2Elements,
    (s1, s2) => new { Value1 = s1.Value, Value2 = s2.Value });

如果您使用的是.NET 3.5或更早版本,则编写Zip扩展名不是太困难:

If you're using .NET 3.5 or earlier, it's not too difficult to write the Zip extension:

public static IEnumerable<TResult> Zip<TFirst, TSecond, TResult>(
    this IEnumerable<TFirst> first,
    IEnumerable<TSecond> second,
    Func<TFirst, TSecond, TResult> resultSelector)
{
    using (var firstEnumerator = first.GetEnumerator())
    using (var secondEnumerator = second.GetEnumerator())
    {
        while ((firstEnumerator.MoveNext() && secondEnumerator.MoveNext()))
        {
            yield return resultSelector(firstEnumerator.Current,
                secondEnumerator.Current);
        }
    }
}

这篇关于使用LINQ to XML,如何根据序数位置连接两组数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆