---
title: "Search sorted List&lt;Long&gt; for closest and less than"  
description: "Search sorted List&lt;Long&gt; for closest and less than"  
author: "Lady Bird Johnson"  
published: 2013-10-05  
updated: 2013-10-05  
canonical: https://www.mindstick.com/forum/1617/search-sorted-list-lt-long-gt-for-closest-and-less-than  
category: "c#"  
tags: ["c#"]  
reading_time: 1 minute  

---

# Search sorted List&lt;Long&gt; for closest and less than

Consider some [long](https://www.mindstick.com/articles/44565/white-wedding-dresses-long-prom-dresses) called X and a sorted List<Long>. What is the most [efficient](https://www.mindstick.com/articles/33637/three-tips-for-an-energy-efficient-home-for-2019) [algorithm](https://www.mindstick.com/blog/119/implementing-cryptography-in-c-sharp-dot-net-by-using-sha1-algorithm) to find the [index](https://www.mindstick.com/blog/198/index-in-sql-server) or [value](https://www.mindstick.com/articles/23219/an-optimized-description-adds-value-to-experience-and-in-turn-effectively-guest-posting-packages) in the List<Long> that is (i) less than X, and (ii) The closest to X on the number line (assuming [condition](https://www.mindstick.com/forum/12711/select-query-with-and-condition) (i) has been satsified)?

For example this could be a [problem](https://yourviews.mindstick.com/view/81399/tackling-the-problem-of-unemployment-during-corona-pandemic) [setup](https://www.mindstick.com/articles/426/how-to-create-a-setup-project-for-windows-application):

```
long X = 500;
List<Long> foo = new Arraylist<Long>();
foo.add(450L);
foo.add(451L);
foo.add(499L);
foo.add(501L);
foo.add(550L);

Collections.sort(foo); // It's always sorted.
```

I would like the algorithm to either return 499 or to return the index associated with 499 (in this casei=2).\

## Replies

### Reply by Hank Greenberg

If 499 is unique than, use indexOf(Object) method.


---

Original Source: https://www.mindstick.com/forum/1617/search-sorted-list-lt-long-gt-for-closest-and-less-than

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
