Home > Mobile >  Remove possible null warning of nulleable v
Remove possible null warning of nulleable v

Time:12-02

I have a linq query where I map some models as:

return campaigns
            .Select(
                c =>
                    new CampaignSelectViewModel
                    {
                        CampaignId = c.CampaignId,
                        CampaignName = c.Name,
                        ..
                        CampaignStations = c.CampaignStations
                            .Select(cs => cs.Station)
                            .Select(
                                s =>
                                    new StationSelectViewModel
                                    {
                                        StationId = s.StationId,
                                        ...
                                    }
                            )
                            .ToList()
                    }
            )
            .ToList();

The IDE marks the s as possible null because Station on campaign station can be null, so I want to validate it if station is not null then assign the StationSelectModel, how can I achieve that?:

CodePudding user response:

If you want to return something when it is null, then

return campaigns
            .Select(
                c =>
                    new CampaignSelectViewModel
                    {
                        CampaignId = c.CampaignId,
                        CampaignName = c.Name,
                        ..
                        CampaignStations = c.CampaignStations
                            .Select(cs => cs.Station)
                            .Select(
                                s =>
                                {
                                    if (s != null)
                                    {
                                        return new StationSelectViewModel
                                        {
                                            StationId = s.StationId,
                                            ...
                                        }
                                    }
                                    else
                                    {
                                        return new StationSelectViewModel
                                        {
                                            StationId = SOMETHING ELSE
                                            ...
                                        }
                                    }
                                }
                            )
                            .ToList()
                    }
            )
            .ToList();
  • Related