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

标签 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> 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;
        }
    }
}

关于c# - 使用 Linq 和 C#,是否可以加入两个列表但在每个项目处交错?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1758404/

相关文章:

c# - 在转换为 SQL 之前在 C# 中评估的 LINQ 查询?

c# - 没有 .svc 的 WCF 服务相对 uri

entity-framework - 如何编写需要子查询的 Linq 查询?

c# - 如何实现我自己的字节数组创建和处理

c# - 绘制图像时 : System. Runtime.InteropServices.ExternalException: GDI 中发生一般性错误

.net - 如何在 C# 中编码(marshal) int*?

c# - Linq 从属性符合条件的列表中选择

c# - LINQ 是否使用 DataRelations 来优化联接?

c# - 尝试引用 LINQ 命名空间时出现异常

c# - 发送多个并行 Web 请求