Calculating the difference of elements in an array

Is there a way to calculate the difference between elements in an array and check if there is a difference> 1 using LINQ?

So, if you have an array {1,2,3,5,8,9}, you want to know what is the difference between each of the elements and only get the elements that follow each up, so the difference == 1.

Is this possible with LINQ?

+3
source share
3 answers

You can use an overload .Wherethat uses an index - of course, it also uses the fact that numbers are an array with an indexing operator:

int[] numbers = new[] { 1, 2, 3, 5, 8, 9 };
int[] followNumbers = numbers.Where((x, idx) => 
                                (idx >=1 && numbers[idx-1] == x-1 
                                 || (idx < numbers.Length-1 
                                     && numbers[idx+1] == x+1) ))
                              .ToArray();

, "" a > 1 - , , , .

{1,2,3,8,9} .

+4

Enumerable.Zip

var testArray = new int[] { 1, 2, 3, 5, 8, 9 };
var withNextElement = testArray.Zip(testArray.Skip(1), Tuple.Create);
var onlyOffByOne = withNextElement.Where(x => x.Item1 + 1 == x.Item2);
var withMatchingNext = onlyOffByOne.Select(x => x.Item1);
foreach(var item in withMatchingNext)
    Console.WriteLine(item);

1
2
8

?

9 ? {1,2,3,5,8}?

+3
    int[] a = { 1, 2, 3, 5, 8, 9 };
    var b = a.Where((item, index) =>
    {
        if(index + 1 == a.Length)
            return false;

        return item - a[index + 1] == -1;
    }).ToArray();
+1
source

Source: https://habr.com/ru/post/1793418/


All Articles