Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
551 views
in Technique[技术] by (71.8m points)

linq - Group items in pairs

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Well, you could do:

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

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);
        }
    }
}

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...