Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# & LINQ, Select two (consecutive) items at once [duplicate]

Tags:

c#

linq

Using LINQ on an ordered set (array, list), is there a way to select or otherwise use two consecutive items? I am imagining the syntax:

list.SelectTwo((x, y) => ...)

Where x and y are the items at index i and i + 1 in the list/array. There may be no way to do this, which I accept as a possibility, but I would at least like to say I tried to find an answer.

I am aware that I could use something other and LINQ to achieve this.

Thank you in advance.

like image 572
YourGamerMom Avatar asked Feb 10 '16 22:02

YourGamerMom


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

What is C in C language?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.

Is C language easy?

C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.


2 Answers

System.Linq.Enumerable.Zip combines two IEnumerables by pairing up the i-th element for each i. So you just need to Zip your list with a shifted version of it.

As a nice extension method:

using System.Collections.Generic;
using System.Linq;

static class ExtMethods
{
    public static IEnumerable<TResult> SelectTwo<TSource, TResult>(this IEnumerable<TSource> source,
                                                                        Func<TSource, TSource, TResult> selector)
    {
        return Enumerable.Zip(source, source.Skip(1), selector);
    }
}

Example:

Enumerable.Range(1,5).SelectTwo((a,b) => $"({a},{b})");

Results in:

(1,2) (2,3) (3,4) (4,5)
like image 170
m3tikn0b Avatar answered Oct 01 '22 18:10

m3tikn0b


Another answer presents a nice and clean solution using LINQ's Skip and Zip.

It is absolutely correct, but I'd like to point out that it enumerates the source twice. That may or may not matter, depending on each individual use case. If it matters for your case, here's a longer alternative that is functionally equivalent but enumerates the source once:

static class EnumerableUtilities
{
    public static IEnumerable<TResult> SelectTwo<TSource, TResult>(this IEnumerable<TSource> source,
                                                                   Func<TSource, TSource, TResult> selector)
    {
        if (source == null) throw new ArgumentNullException(nameof(source));
        if (selector == null) throw new ArgumentNullException(nameof(selector));

        return SelectTwoImpl(source, selector);
    }

    private static IEnumerable<TResult> SelectTwoImpl<TSource, TResult>(this IEnumerable<TSource> source,
                                                                        Func<TSource, TSource, TResult> selector)
    {
        using (var iterator = source.GetEnumerator())
        {
            var item2 = default(TSource);
            var i = 0;
            while (iterator.MoveNext())
            {
                var item1 = item2;
                item2 = iterator.Current;
                i++;

                if (i >= 2)
                {
                    yield return selector(item1, item2);
                }
            }
        }
    }
}

Example:

var seq = new[] {"A", "B", "C", "D"}.SelectTwo((a, b) => a + b);

The resulting sequence contains "AB", "BC", "CD".

like image 29
Theodoros Chatzigiannakis Avatar answered Oct 01 '22 18:10

Theodoros Chatzigiannakis