Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need sorted dictionary designed to find values with keys less or greater than search value

I need to have objects sorted by price (decimal) value for fast access. I need to be able to find all objects with price more then A or less than B. I was thinkg about SortedList, but it does not provide a way to find ascending or descending enumerator starting from given key value (say give me all objects with price less than $120).

Think of a system that accepts cars for sale from sellers and stores them into that collection. Then buyers want to find cars cheaper than $1000.

Basically what i need is tree-based collection and functionality to find node that is smaller\greater\equal to provided key.

Please advice.

like image 993
Captain Comic Avatar asked Apr 23 '10 11:04

Captain Comic


3 Answers

You can use BinarySearch on SortedList to search first and last indexes satisfying your conditions and then just get range of items from list.

like image 132
Alex Avatar answered Oct 14 '22 23:10

Alex


The answer depends on your usage patterns. If this a one-off exercise of consuming an unsorted input set and finding suitable objects, you are much better off just using LINQ:

list.Where(e => A < e.Price || e.Price < B);

If the list is static, and you want to query multiple ranges, then stick the objects into an array, sort them by price, and then use a binary chop to find ranges of interest.

like image 40
Marcelo Cantos Avatar answered Oct 14 '22 22:10

Marcelo Cantos


Please think of a SortedList. Alternatively you can use just any collection and query it with LINQ. For example plain generic List:

        List<Int32> tempList = new List<Int32>();

        tempList.Where(singleItem => singleItem > 100)
            .ToList<Int32>();
like image 2
Piotr Justyna Avatar answered Oct 14 '22 21:10

Piotr Justyna