stingray-11
stingray-11

Reputation: 448

searching C# array of objects for nearest float value

So I have an array of objects, each with a property called value.... I want to be able to search through this array of objects and then run some code only if it can find a value within a certain range.

For example if I supply a value of 25 and I'm searching within a range of 5 (the difference between 25 and the closest value is < 5), and I have this:

array[0].value = 16
array[1].value = 19
array[2].value = 22

then it would execute some code that I want.

Is there any simple way to go about this? Thanks!

Upvotes: 0

Views: 583

Answers (3)

Nashibukasan
Nashibukasan

Reputation: 2028

If you only care that one value in the array needs to be within a target amount, you could do something like:

        float[] array = {1.0f, 10.0f, 15.7f};
        float target = 25;
        float range = 5;

        foreach (float f in array)
        {
            float temp = f - target;
            if (temp < range && temp > (-range))
            {
                //execute code here
            }
        }

EDIT: I at first assumed these were floats for some reason, but the same code is the logic for any number based datatype.

Upvotes: 0

Richard Schneider
Richard Schneider

Reputation: 35477

Assuming that X is the class of the objects in array.

public void WhenInRange(IEumerable<X> array, int value, int delta, Action<X> action)
{
   var s = value - delta;
   var e = value + delta;
   foreach (var match in array.Where(x => s <= x.value && e <= x.value))
      action(match);
}

To print all matches do:

WhenInRange(array, 25, 5, (x) => Console.WriteLine(x.value));

Upvotes: 2

Matt Ball
Matt Ball

Reputation: 359876

In pseudocode:

for every element of the array:
    let d = the absolute value of (element.value - target_value)
    if d is less than min_difference:
        do something
        break the loop

That's it. The corresponding values in your question would be target_value of 25 and min_difference of 5.

Upvotes: 0

Related Questions