c# - 如何在 C# 中使用多个列表选择检查 null 条件?

标签 c# json asp.net-core

在我的选择语句中,我想检查 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 是否不为 null show ip。

最佳答案

我认为你可以使用“?”运算符

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

或者

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

这种情况下也不异常(exception),只有当 Ingress 不为 null 时才给 IP 赋值

关于c# - 如何在 C# 中使用多个列表选择检查 null 条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59879676/

相关文章:

c# - ShowHeaderWhenEmpty、EmptyDataText 和 EmptyDataTemplate 在 gridview 中不起作用

c# - 如何序列化 List<object> 同时转义特殊字符?

java - 从 MySQL 获取数据到 Android 应用程序

c# - 在 Raspberry Pi 上 dockerize .net core mvc 应用程序后,wwwroot 文件夹中没有静态文件

c# - EF core 在 ASP.net core 多层架构中添加迁移

c# - 如何获取 GridView 上 DataSet.DataTable 的总计?

c# - 依赖 HTTPContext 的 MVC 测试操作

c# - 如何使用 jquery 和 Web API 上传文件

asp.net-core - ASP .NET Core 2 中的字符串修剪模型绑定(bind)器

C# 亚马逊上传提要,将产品与现有产品匹配?