c# - 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
解决方案
您有两种选择:专业解决方案和学生解决方案。
学生解决方案:
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()));
推荐阅读
- kubernetes - 更新 DaemonSet 而无需像部署那样停机
- ruby-on-rails - Rails 4 和关联现有嵌套模型时的行为变化
- arrays - VBA - 比较多维数组中的元素
- reactjs - 使用 React Styled-Components 导入 scss 变量的最佳方法?
- azure - 如何在 Azure 服务结构的同一端口上托管多个 Web API 服务
- c++ - 类方法接受表示各种数量参数的函数的 lambda
- node.js - 运行 lerna bootstrap -- 在 Windows 上提升命令时不允许操作错误 npm
- python - 如何简单地将 mhtml 文件转换为 html 文件
- c++ - C ++如何使用指向向量指针的指针
- r - 使用 glmnet 为给定数量的预测变量找到优化模型