开发者

Calculate difference of elements in array

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 a开发者_开发问答nd 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?


    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();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜