how do i check to see if a double array contains a certain double in c#

Viewed 236

I'm using this code right now

        double[] LocationsDown = { 40, 85, 130, 175, 220, 265, 310, 355 };
        double[] LocationsUp = { 50, 95, 140, 185, 230, 275, 320, 5 };
        double curretangle = Math.Round(targetAngle);

        if (LocationsDown == curretangle) // <- Compile Time Error here
        {
            //thing
        }

but it says that

" Operator '==' cannot be applied to operands of type 'double[]' and 'double' "

I do not understand the correct way to check if the array contains said double I feel like it's going to be an easy fix I just can't put my finger on it.

2 Answers

In general case we have to compare double values with some tolerance:

 if (Math.Abs(someValue - valueToCheck) <= tolerance) {...}

When working with collections we can use Linq to query them:

 using System.Linq;

 ...

 double tolerance = 1e-6; 

 bool contains = LocationsDown.Any(item => Math.Abs(item - curretangle) <= tolerance);

Use .Contains:

if (LocationsDown.Contains(curretangle))
Related