繁体   English   中英

我可以根据变量(布尔)在 if 语句中设置逻辑运算符吗? C#

[英]Can I set a logical operator inside an if statement depending on a variable (bool)? C#

这是我的代码:

        static int SearchWithCondition(List<MyClass> list, bool someBool)
        {
            MyClass found = list[0];
            foreach (var item in list)
            {
                if (someBool)
                {
                    if (item.id < found.id)
                    {
                        found = item;
                    }
                }
                else
                {
                    if (item.id > found.id)
                    {
                        found = item;
                    }
                }
            }
            return found.id;
        }

如您所见, someBool 确定它是否会搜索更小 (<) 或更大 (>),这是唯一的区别。 我怎样才能使它不那么“丑陋”和更短? 我试图弄清楚如何根据布尔值替换 if 中的运算符,但我找不到。

您不需要替换操作员; 你只需要 select 正确的比较表达式。 有几种方法可以做到这一点。

if ((someBool && item.id < found.id) || item.id > found.id)
{
    found = item;
}

或者,使用三元运算符:

if (someBool 
       ? item.id < found.id 
       : item.id > found.id)
{
    found = item;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM