我有 3 个属性(为了简单起见,有 3 个变量) 方法FillOrNotFill说明了 strings a, b,c可以为空,也可以不为空或 null。
我需要验证一种情况,即只有一个字符串必须不为空且不为 null,而其他字符串必须为空或 null 。
我可以用多个条件来做到这一点(比如在那些多个 if 中),但我正在寻找一些更优雅的解决方案。
string x = "someValue"
string a = FillOrNotFill(x);
string b = FillOrNotFill(x);
string c = FillOrNotFill(x);
//sample of multiple if's
if((!string.IsNullOrWhiteSpace(payload.a) && string.IsNullOrWhiteSpace(payload.b) && string.IsNullOrWhiteSpace(payload.c))
|| (!string.IsNullOrWhiteSpace(payload.b) && string.IsNullOrWhiteSpace(payload.a) && string.IsNullOrWhiteSpace(payload.c)
|| (!string.IsNullOrWhiteSpace(payload.c) && string.IsNullOrWhiteSpace(payload.b) && string.IsNullOrWhiteSpace(payload.a)
)))
{
//valid!
}
Run Code Online (Sandbox Code Playgroud)
你可以将它们放入一个集合中,然后就很简单了:
string[] all = {a, b, c};
bool result = all.Count(s => !string.IsNullOrWhiteSpace(s)) == 1;
Run Code Online (Sandbox Code Playgroud)
如果有数千个,您可以通过以下方式提高效率:
bool result = all.Where(s => !string.IsNullOrWhiteSpace(s)).Take(2).Count() == 1;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
952 次 |
| 最近记录: |