【问题标题】:How to check null condition with multiple list select in c#?如何在 C# 中使用多个列表选择检查空条件?
【发布时间】:2020-01-23 13:25:57
【问题描述】:

在我的选择语句中,我想检查 null 或空。

        [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 结果是:

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

我知道在我的情况下 ingress 是空的,在这种情况下我得到空引用异常。我需要检查入口,如果它不为空,则显示 ip。

【问题讨论】:

  • 你试过用'?.'句法?例如item.Status.LoadBalancer?.Ingress.Select(x => x.Ip)

标签: c# json asp.net-core


【解决方案1】:

我认为你可以使用“?”运营商

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

或者

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

在这种情况下,不会有例外,只有当 Ingress 不为空时,您才会为 IP 赋值

【讨论】:

  • 仅当 Ingress 不为 null no 时?
【解决方案2】:

尝试使用?操作符:

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-30
    • 2018-04-28
    相关资源
    最近更新 更多