使用Linq和C#,是否可以连接两个列表但在每个项目处交错?

使用Linq和C#,是否可以连接两个列表但在每个项目处交错?,c#,.net,linq,C#,.net,Linq,具有两个相同对象类型的列表。我想使用交错模式将它们连接起来,其中第一个列表的I项由第二个列表的j项分隔 实质上: 第一名单 {a,b,c,d,e,f,g,h} 第二份名单 {0,1,2,3,4} 其中,第一个列表的分组计数为3,第二个列表的分组计数为2 导致 {a,b,c,0,1,e,f,g,2,3,h,4} 这在Linq中是可能的吗?Linq本身没有什么可以做到这一点的——这似乎是一个非常专门的要求——但它很容易实现: public static IEnumerable<T> In

具有两个相同对象类型的列表。我想使用交错模式将它们连接起来,其中第一个列表的I项由第二个列表的j项分隔

实质上:

第一名单

{a,b,c,d,e,f,g,h}

第二份名单

{0,1,2,3,4}

其中,第一个列表的分组计数为3,第二个列表的分组计数为2

导致

{a,b,c,0,1,e,f,g,2,3,h,4}


这在Linq中是可能的吗?

Linq本身没有什么可以做到这一点的——这似乎是一个非常专门的要求——但它很容易实现:

public static IEnumerable<T> InterleaveWith<T>
   (this IEnumerable<T> first, IEnumerable<T> second,
    int firstGrouping, int secondGrouping)
{
    using (IEnumerator<T> firstIterator = first.GetEnumerator())
    using (IEnumerator<T> secondIterator = second.GetEnumerator())
    {
        bool exhaustedFirst = false;
        // Keep going while we've got elements in the first sequence.
        while (!exhaustedFirst)
        {                
            for (int i = 0; i < firstGrouping; i++)
            {
                 if (!firstIterator.MoveNext())
                 {
                     exhaustedFirst = true;
                     break;
                 }
                 yield return firstIterator.Current;
            }
            // This may not yield any results - the first sequence
            // could go on for much longer than the second. It does no
            // harm though; we can keep calling MoveNext() as often
            // as we want.
            for (int i = 0; i < secondGrouping; i++)
            {
                 // This is a bit ugly, but it works...
                 if (!secondIterator.MoveNext())
                 {
                     break;
                 }
                 yield return secondIterator.Current;
            }
        }
        // We may have elements in the second sequence left over.
        // Yield them all now.
        while (secondIterator.MoveNext())
        {
            yield return secondIterator.Current;
        }
    }
}
公共静态IEnumerable InterleaveWith
(这个IEnumerable第一,IEnumerable第二,
int firstGrouping,int secondGrouping)
{
使用(IEnumerator firstIterator=first.GetEnumerator())
使用(IEnumerator secondIterator=second.GetEnumerator())
{
bool排气装置FIRST=错误;
//在第一个序列中有元素时继续。
而(!排风优先)
{                
for(int i=0;i
除了Marc的建议之外,这里还有一个链接展示了如何实现zip扩展方法:我不相信zip在这里能起作用。。。可能是Zip与分区运算符结合使用…
Zip
如果您对
Zip
的结果应用
SelectMany
,将每个元组展开为一个序列,则可以使用。@Stecy:第一个版本中有一个错误。试试这个,你还需要继续努力;firstGrouping和secondGrouping是整数,而不是在for循环中使用的迭代器。但这是解决这个问题的最好方法。@Randolpho:Fixed(这只是一次。)刚刚检查过,现在可以编译了。我真的应该试着养成在发布前编译的习惯…编译很好,但没有给出预期的结果。似乎在返回while循环的顶部时跳过了第一个列表中的一个元素。。。