0

I am trying to incorporate a conditional operation based of the value stored in a string variable. For example out of a set of values I have , I am trying to implement it such that when the string value = ">=2.5"; it will first check if a value corresponding to 2.5 is available as that is the minimum value, if that is true it will check what other values are greater than 2.5 and get the result to the largest value out of the List of values.

Here is what I have tried thus far and I'm currently stuck implementing the logic to get the greatest value out of the set of numbers

static List<double> values = new List<double>();

        static void Main(string[] args)
        {
            values.Add(1.0);
            values.Add(2.0);
            values.Add(2.2);
            values.Add(2.5);
            values.Add(5.0);
            values.Add(5.5);

            string value = ">=2.5";

            if (value.Contains(">="))
            {
                value = value.Replace(">=", "").Trim();


                if (values.Contains(Convert.ToDouble(value)))
                {
                    //Logic should be incorporated
                }


            }


        }

in this case I would expect the greatest value to be 5.5.

Would appreciate any help on this

Devss
  • 67
  • 7
  • `values.Contains` finds if the list contains an exact value (in this case 2.5). You might want to try iterating through each item comparing it to your desired value, or use LINQ (i.e. `values.Any(...)`) – ProgrammingLlama Jan 16 '20 at 01:05
  • `var largestNumGtEqValue = values.Max(v => v >= value);` – Rufus L Jan 16 '20 at 01:19
  • Does [this](https://stackoverflow.com/a/826435) answer your question? – timur Jan 16 '20 at 01:58

1 Answers1

0

You have two options: the Professional solution and the Student solution.

Studant Solution:

        values.Add(1.0);
        values.Add(2.0);
        values.Add(2.2);
        values.Add(2.5);
        values.Add(5.0);
        values.Add(5.5);

        string value = ">=2.5";

        if (value.Contains(">="))
        {
            var valueDouble = Convert.ToDouble(value.Replace(">=", "").Trim());//IMPORT THECONVERSION TO DOUBLE!

            double greatestVersion = 0;
            foreach (var item in values)
            {
                if (item >= valueDouble)
                    greatestVersion = item;
            }

            Console.WriteLine($"The greatest version is " + greatestVersion);
        }

Professional Solution:

var greatestVersion = values.Max(x => x >= Convert.ToDouble(value.Replace(">=", "").Trim()));