使用Linq和C#,是否可以加入两个列表,但每个项目都有交错?

Sté*_*écy 4 .net c# linq

有两个相同对象类型的列表.我想用其中的交织图案加入他们的项目的第一个列表中被分离Ĵ项目从第二个列表.

在本质上:

第一个清单

{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有可能吗?

Jon*_*eet 10

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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)