5

I have a line vector file and I need to select two lines with the longest length using expression. I am familiar with selecting the line with the longest length:

length($geometry) = maximum(length($geometry))

enter image description here

But how to select the longest and second-longest line using an expression?

1 Answer 1

7

Use this expression:

$length >= array_sort(array_agg($length), 0)[1]

Explanation

  1. Create an array of the length of each line with array_agg() and $length
  2. Sort the value by a length with array_sort() with the ascending parameter set to 0 (false), thus ordering in descending order
  3. Get the second element (second longest line): as array-index starts with 0 for the first element, use the index operator [1]
  4. Check if the current feature's length ($length) is equal or longer (>=) than this second-longest line

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.