使用LINQ和C#,是否有可能加入两个列表,但与交织在每个项目?有可能、但与、两个、项目

2023-09-04 12:31:14 作者:让情敌当我伴郎

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

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 items from the second list.

在本质:

首先列出

{A,B,C,D,E,F,G,H}

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

第二个列表

{0,1,2,3,4}

{0, 1, 2, 3, 4}

其中对于所述第一列表中的分组计数为3和用于第二列表是2

where the grouping count for the first list is 3 and for the second list is 2.

致使

{A,B,C,0,1,E,F,G,2,3,小时,4}

C 项目使用LINQ to entities 连接MySQL数据库,求大神解答

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

这可能与LINQ的?

推荐答案

有内LINQ本身无关,这一点 - 它似乎是一个pretty的特殊要求 - 但它很容易实现:

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;
        }
    }
}
 
精彩推荐