使用LINQ to XML,我怎么能加入基于序号位置两组数据?(Using LINQ to XML,

2019-09-25 16:47发布

使用LINQ to XML,我怎么能加入基于序号位置两组数据?

<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 “在相同的记录。

Answer 1:

这是什么Enumerable.Zip扩展确实在.NET 4.您会写像这样(假设这是整个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扩展:

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


Answer 2:

下面是使用选择的过载的另一种方法,其中将包括一个元素的索引

XElement set1 = document.Root.Element("set1");
XElement set2 = document.Root.Element("set2");

var query = from value1 in set1.Descendants("value").Select((ele, idx) => new { Value = ele.Value, Index = idx })
            join value2 in set2.Descendants("value").Select((ele, idx) => new { Value = ele.Value, Index = idx })
            on value1.Index equals value2.Index
            select new { Value1 = value1.Value, Value2 = value2.Value };


文章来源: Using LINQ to XML, how can I join two sets of data based on ordinal position?