I have an object that looks like this:
Public Class MyObject
Public Property Key as Intger
get 'Elided for clarity
set
End Property
Public Property Value as String
get
set
End Property
Private key as Intger
Private value as String
End Class
Then I have List(Of MyObject) where each Key has some value… If you sort them, you’ll have a series of keys that follow each other, but the difference between each Key might be > 1. Now I get a subset of this list and I want to (after sorting by Key) check if the difference between each MyObject.Key is no greater then 1 and get this subset.
What would be the best way to do so?
You can use this trick with Zip and Skip to get the differences, and then just test them:
Basically this pairs up a sequence with itself shifted one element ahead, and calculates the difference. Beware that this evaluates
subsettwice. It may or may not be important.If the keys are unique, you can do this even easier:
This works because, knowing that they’re sorted, unique, and their differences are not greater than 1, then the keys must be in sequence. So, the number of keys is one more than the difference between the last and the first (e.g. {11,12,13,14} => 14-11 = 4-1).