取两个可空值中的较大者 [英] Take the greater of two nullable values

查看:58
本文介绍了取两个可空值中的较大者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有两个可为空的整数:

Suppose I have two nullable integers:

int? a = 10;
int? b = 20;

我想取最大的非空值,这样如果两个值都为空,则结果为空.

I want to take the biggest, non-null value, such that if both values are null, the result is null.

我可以写一些冗长的东西,例如:

I could write something long-winded such as:

int? max;
if (a == null)
{
    max = b;
}
else if (b == null)
{
    max = a;
}
else
{
    max = a > b ? a : b;
}

这对我来说感觉有点太笨重(并且可能容易出错).返回更大值的最简单方法是什么,这也说明了空值的可能性?

This feels a little too clunky (and possibly error-prone) for my liking. What's the simplest way to return the greater value, which also accounts for the possibility of null values?

推荐答案

这适用于任何可为 null 的:

This works for any nullable:

Nullable.Compare(a, b) > 0 ? a : b;

这篇关于取两个可空值中的较大者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆