我可以根据变量(bool)在if语句中设置逻辑运算符吗?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决定它是搜索更小(<(还是更大(>(,这是唯一的区别。我怎样才能让它少一点";丑陋的";更短?我试图找出如何根据bool替换if中的运算符,但我找不到。

您不需要替换运算符;您只需要选择正确的比较表达式。有几种方法可以做到这一点。

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

或者,使用三元运算符:

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

最新更新