Is there a way to calculate the difference between elements in an array and check if difference is > 1 using LINQ?
So if you have an array {1,2,3,5,8,9}, want to know what the difference is between each of the elements and only get the elements that follow each up directly, so difference == 1.
Is this possible using LINQ?
You could use the .Where overload that uses the index - of course this also uses the fact that numbers is an array with an index 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();
Edited to capture all numbers that are part of an "island" of consecutive numbers, with an island size of > 1 - that means you have to look forward and backward from each number to find if either the predecessor or successor is consecutive.
Output is {1,2,3,8,9} in the example case.
You can use some tricks with 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);
gives
1
2
8
How do you want to handle the last element?
Should 9 be included? Should the last element in {1,2,3,5,8} be included?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With