You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用三元运算符时,如何防止不符合条件的项存入集合(不存null)

解决三元运算符场景下集合避免存入null的问题

你当前的代码会在条件不满足时向集合中添加null,导致列表包含无效的null元素。以下几种方法可以解决这个问题,只保留符合条件的有效项:

方法一:逐个判断添加元素

直接初始化空列表,仅当条件满足时才添加对应元素,从根源避免null进入集合:

if (part.IsFailure || customer.IsFailure || provider.IsFailure)
{
    var invalidFields = new List<InvalidArgumentFieldDetail>();
    
    if (part.IsFailure)
        invalidFields.Add(new InvalidArgumentFieldDetail(nameof(part.Id), part.Error.ErrorCode.ToString(), part.Error.Message, null));
    if (customer.IsFailure)
        invalidFields.Add(new InvalidArgumentFieldDetail(nameof(customer.Id), customer.Error.ErrorCode.ToString(), customer.Error.Message, null));
    if (provider.IsFailure)
        invalidFields.Add(new InvalidArgumentFieldDetail(nameof(provider.Id), provider.Error.ErrorCode.ToString(), provider.Error.Message, null));
    
    return BadRequest(new InvalidArgumentDetails(invalidFields));
}

(注:原代码中part1.Error应为笔误,修正为part.Error)

方法二:用LINQ过滤null元素

保留你原本的三元写法,在集合初始化完成后,通过Where过滤掉所有null元素:

if (part.IsFailure || customer.IsFailure || provider.IsFailure)
{
    var invalidFields = new List<InvalidArgumentFieldDetail>()
    {
        part.IsFailure ? new InvalidArgumentFieldDetail(nameof(part.Id), part.Error.ErrorCode.ToString(), part.Error.Message, null) : null,
        customer.IsFailure ? new InvalidArgumentFieldDetail(nameof(customer.Id), customer.Error.ErrorCode.ToString(), customer.Error.Message, null) : null,
        provider.IsFailure ? new InvalidArgumentFieldDetail(nameof(provider.Id), provider.Error.ErrorCode.ToString(), provider.Error.Message, null) : null,
    }
    .Where(item => item != null)
    .ToList();
    
    return BadRequest(new InvalidArgumentDetails(invalidFields));
}

方法三:使用C# 8.0+的条件集合初始化

如果你的项目使用C# 8.0及以上版本,可以直接在集合初始化器中用if条件控制元素添加,写法更简洁:

if (part.IsFailure || customer.IsFailure || provider.IsFailure)
{
    return BadRequest(new InvalidArgumentDetails(new List<InvalidArgumentFieldDetail>()
    {
        if (part.IsFailure) new InvalidArgumentFieldDetail(nameof(part.Id), part.Error.ErrorCode.ToString(), part.Error.Message, null),
        if (customer.IsFailure) new InvalidArgumentFieldDetail(nameof(customer.Id), customer.Error.ErrorCode.ToString(), customer.Error.Message, null),
        if (provider.IsFailure) new InvalidArgumentFieldDetail(nameof(provider.Id), provider.Error.ErrorCode.ToString(), provider.Error.Message, null),
    }));
}

这三种方法都能确保集合中只包含符合条件的InvalidArgumentFieldDetail实例,不会出现null元素。你可以根据项目的C#版本和代码风格选择合适的方式。

内容的提问来源于stack exchange,提问作者SimasVe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 00:26:32