首页 > 解决方案 > Logic operations in string value which include symbols

问题描述

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

标签: c#.netstringlogicoperators

解决方案


您有两种选择:专业解决方案和学生解决方案。

学生解决方案:

        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);
        }

专业解决方案:

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

推荐阅读