C# 如何在c中用多列表选择检查空条件?

C# 如何在c中用多列表选择检查空条件?,c#,json,asp.net-core,C#,Json,Asp.net Core,在select语句中,我想检查null或empty [HttpGet("service")] public IActionResult GetService() { var config = KubernetesClientConfiguration.BuildConfigFromConfigFile("project.conf"); IKubernetes client = new Kubernet

在select语句中,我想检查null或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);
        }
结果是:

 {
        "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"
                    }
                ]
            }
        }       
    }

我知道在我的例子中,入口是空的,在这个例子中,我得到了空引用异常。我需要检查入口是否为空,显示ip。

我想你可以使用吗?接线员

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

在这种情况下,将不会出现异常,只有入口不为null时,您才会将值分配给IP

是否尝试使用?接线员:

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)
    };
这个接线员?在C 6及更高版本中提供。在您的示例中,它意味着:

Ip = (item.Status.LoadBalancer.Ingress == null ? null  : item.Status.LoadBalancer.Ingress)

你试过使用“?”语法吗?e、 g.item.Status.LoadBalancer?.Ingress.Selectx=>x.I仅当Ingress不为空时否?
Ip = (item.Status.LoadBalancer.Ingress == null ? null  : item.Status.LoadBalancer.Ingress)