Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Equivalent of VLOOKUP in C#

Ive been struggling to figure out what the correct way to do this is.
I have a table in Excel that relates Motor horsepower size to the amount of space it takes up.

enter image description here

I would like to implement a lookup function of this information in a C# Windows Form that I am writing.
I want to create a function that has a single argument passed to it (double HP). It would lookup if the motor HP falls in-between "Low" and "High" and then it would return the value in the "Space Factor" column. I feel pretty silly for not knowing the best way to do this. I want to avoid IF/Else statements as it doesnt seem like the right approach. Additionally, interfacing with Excel to do the lookup also seems a little silly.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How would you interface with a data table like this?

>Solution :

You should create an class to represent your rows, you can then add each object to a list. If you have few items you can just use Linq:

var hp = 20;
var objects = new List<MyClass>(){...};
var foundObj = objects.FirstOrDefault(o => hp > o.HpLow && hp < o.HpHigh);
if(foundObj != null){
   // Found object!
}

If you have lots of rows you can instead sort the list by the HpHigh, and use BinarySearch to find the item without iterating over all items, but it requires a custom comparer and is a bit more complex.

If hp-ranges can overlap for you need some way to determine which of the rows is the most fitting one, so I’m just going to assume ranges do not overlap.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading