Using Linq and C#, is it possible to join two lists but with interleaving at each item?

前端 未结 1 715
猫巷女王i
猫巷女王i 2021-01-20 01:23

Having two lists of same object type. I want to join them using an interleave pattern where i items of the first list are separated by j it

相关标签:
1条回答
  • 2021-01-20 01:31

    There's nothing within LINQ itself to do this - it seems a pretty specialized requirement - but it's fairly easy to implement:

    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;
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题