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

如何解决LINQ查询中Station可能为null的警告并过滤空值?

解决LINQ映射中Station可为null的过滤问题

你可以通过在映射前过滤掉Station为null的项来解决这个问题,具体有两种简洁的实现方式:

方式一:先过滤再提取Station

直接在Select(cs => cs.Station)之前添加Where条件,排除cs.Station为null的CampaignStation,这样后续映射时s必然不为null:

return campaigns
    .Select(c => new CampaignSelectViewModel
    {
        CampaignId = c.CampaignId,
        CampaignName = c.Name,
        // 其他属性...
        CampaignStations = c.CampaignStations
            .Where(cs => cs.Station != null) // 过滤掉Station为null的项
            .Select(cs => cs.Station)
            .Select(s => new StationSelectViewModel
            {
                StationId = s.StationId,
                // 其他Station属性...
            })
            .ToList()
    })
    .ToList();

方式二:提取后过滤(适用于需要保留中间步骤的场景)

如果先提取Station再过滤,也能达到同样效果,只是逻辑顺序不同:

return campaigns
    .Select(c => new CampaignSelectViewModel
    {
        CampaignId = c.CampaignId,
        CampaignName = c.Name,
        // 其他属性...
        CampaignStations = c.CampaignStations
            .Select(cs => cs.Station)
            .Where(s => s != null) // 过滤掉null的Station
            .Select(s => new StationSelectViewModel
            {
                StationId = s.StationId,
                // 其他Station属性...
            })
            .ToList()
    })
    .ToList();

两种方式都能确保只有当Station不为null时,才会创建对应的StationSelectViewModel,同时消除IDE的null警告。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 13:45:47