skip to Main Content

In my select statement i would like to check null or empty.

        [HttpGet("service")]
        public IActionResult GetService()
        {
            var config = KubernetesClientConfiguration.BuildConfigFromConfigFile("project.conf");
            IKubernetes client = new Kubernetes(config);
            var volumeList = client.ListNamespacedService("default");
            var result = from item in volumeList.Items
                select new
                {
                    MetadataName = item.Metadata.Name,
                    Namespace = item.Metadata.NamespaceProperty,
                    Age = item.Metadata.CreationTimestamp,
                    Type = item.Spec.Type,
                    All = item.Status,
                    Ip = item.Status.LoadBalancer.Ingress.Select(x => x.Ip)
                };
            return Ok(result);
        }

Json result is :

 {
        "metadataName": "cred-mgmt-redis-slave",
        "namespace": "default",
        "age": "2019-12-20T09:50:11Z",
        "type": "ClusterIP",
        "all": {
            "loadBalancer": {
                "ingress": null
            }
        }       
    },
    {
        "metadataName": "jenkins",
        "namespace": "default",
        "age": "2020-01-01T16:38:58Z",
        "type": "LoadBalancer",
        "all": {
            "loadBalancer": {
                "ingress": [
                    {
                        "hostname": null,
                        "ip": "185.22.98.93"
                    }
                ]
            }
        }       
    }

I know in my case ingress is null and in this case I got null reference exception. I need to check ingress if it is not null show ip.

2

Answers


  1. I think you can use “?” operator

    Ip = item.Status.LoadBalancer.Ingress?.Select(x => x.Ip)
    

    Or

    Ip = item.Status?.LoadBalancer?.Ingress?.Select(x => x.Ip)
    

    In this case, there will be no exception and you will assign value to IP only if Ingress is not null

    Login or Signup to reply.
  2. Try to use ? operator:

    var result = from item in volumeList.Items
        select new
        {
            MetadataName = item.Metadata?.Name,
            Namespace = item.Metadata?.NamespaceProperty,
            Age = item.Metadata?.CreationTimestamp,
            Type = item.Spec?.Type,
            All = item?.Status,
            Ip = item.Status?.LoadBalancer?.Ingress.Select(x => x.Ip)
        };
    

    This operator ? is available in C# 6 and later. In your example, it means:

    Ip = (item.Status.LoadBalancer.Ingress == null ? null  : item.Status.LoadBalancer.Ingress)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search