c# - 如何将 IEnumerable 中的每两个项目作为一对?

标签 c# list tuples ienumerable

我有 IEnumerable<string>看起来像 {"First", "1", "Second", "2", ... } .

我需要遍历列表并创建 IEnumerable<Tuple<string, string>>元组看起来像:

"First", "1"

"Second", "2"

所以我需要从列表中创建对,我必须如上所述获得对。

最佳答案

实现这一点的惰性扩展方法是:

public static IEnumerable<Tuple<T, T>> Tupelize<T>(this IEnumerable<T> source)
{
    using (var enumerator = source.GetEnumerator())
        while (enumerator.MoveNext())
        {
            var item1 = enumerator.Current;

            if (!enumerator.MoveNext())
                throw new ArgumentException();

            var item2 = enumerator.Current;

            yield return new Tuple<T, T>(item1, item2);
        }
}

请注意,如果元素的数量恰好不是偶数,则会抛出异常。另一种方法是使用此扩展方法将源集合拆分为 2 个 block :

public static IEnumerable<IEnumerable<T>> Chunk<T>(this IEnumerable<T> list, int batchSize)
{

    var batch = new List<T>(batchSize);

    foreach (var item in list)
    {
        batch.Add(item);
        if (batch.Count == batchSize)
        {
            yield return batch;
            batch = new List<T>(batchSize);
        }
    }

    if (batch.Count > 0)
        yield return batch;
}

然后你可以这样做:

var tuples = items.Chunk(2)
    .Select(x => new Tuple<string, string>(x.First(), x.Skip(1).First()))
    .ToArray();

最后,只使用现有的扩展方法:

var tuples = items.Where((x, i) => i % 2 == 0)
    .Zip(items.Where((x, i) => i % 2 == 1), 
                     (a, b) => new Tuple<string, string>(a, b))
    .ToArray();

关于c# - 如何将 IEnumerable 中的每两个项目作为一对?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5239635/

相关文章:

c# - 在 asp.net mvc 的同一 View 中列出和创建

c# - 使用 linq 填充字典

list - Haskell 取列表的升序 (+1) 部分

python - 将元组添加到作为键字典

c# - 如何在 C# 应用程序中使用 HTML5 地理定位

c# - 使用 Linq 查询解析 List<CustomClass> 中的 XML

c# - 防止应用程序关闭

python - 从具有前缀的列表中获取元素

c++ - boost 元组部分迭代?

Python 从元组反转索引列表