成对分组项目 [英] Group items in pairs

查看:47
本文介绍了成对分组项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有项目列表,例如:{ i1, i2, i3, i4, i5, i6, i7 }.
我想获取一个列表,其中每个项目都是源列表中的一对项目:{ {i1, i2}, {i3, i4}, {i5, i6}, {i7} }.
i7是成对的单个项目,因为没有项目i8.
可以用LINQ吗?

I have list of items, for example: { i1, i2, i3, i4, i5, i6, i7 }.
I want to get a list, where every item is a pair of items from source list: { {i1, i2}, {i3, i4}, {i5, i6}, {i7} }.
i7 is a single item in pair because there is no item i8.
Is it possible to do with LINQ?

推荐答案

好吧,你可以做:

var pairs = sequence.Select((value, index) => new { value, index } )
                    .GroupBy(x => x.index / 2, x => x.value)

结果为IGrouping<int, T>,其键为0、1、2等,每个组的内容为一项或两项.

The result is an IGrouping<int, T> with a key of 0, 1, 2 etc and the contents of each group being one or two items.

但是,我可能会编写一个自定义扩展方法:

However, I'd possibly write a custom extension method:

public static IEnumerable<Tuple<T, T>> PairUp<T>(this IEnumerable<T> source)
{
    using (var iterator = source.GetEnumerator())
    {
        while (iterator.MoveNext())
        {
            var first = iterator.Current;
            var second = iterator.MoveNext() ? iterator.Current : default(T);
            yield return Tuple.Create(first, second);
        }
    }
}

这将产生一个元组序列-这里的缺点是,如果该序列具有奇数个项目,则最后一个元组将T的默认值作为第二个"项目.对于仅包含非空值的序列的引用类型,这是可以的,但对于某些序列,则无济于事.

This will yield a sequence of tuples - the downside here is that the final tuple will have the default value for T as the "second" item if the sequence has an odd number of items. For reference types where the sequence only consists of non-null values, that's okay, but for some sequences it wouldn't help.

这篇关于成对分组项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆