如何确定列表是否包含任何对象

时间:2019-04-24 19:17:48

标签: c#

由于某种原因,我无法处理一个简单的IF语句。收到以下错误:

  

运算符==不能应用于类型List<Status>bool的操作数。

我只需要知道上面statusCollection的语句是否为true,然后处理其余的调用。对于C#和.NET还是很新的,所以我正在学习。

预期结果

如果找到statusCollection = statusCollection.Where的任何结果,则运行语句,如果找不到任何内容,则继续控制台输出。

public static void Main(string[] args)
{
    using (var webClient = new WebClient())
    {
        String rawJSON = webClient.DownloadString("https://status.cloud.google.com/incidents.json");
        List<Status> statusCollection = JsonConvert.DeserializeObject<List<Status>>(rawJSON);
        Console.WriteLine(statusCollection + "\n\nLast Run: " + DateTime.Now.ToString("MM/dd/yyyy h:mm tt\n"));

        statusCollection = statusCollection.Where(r => r.Service_key == "cloud-networking" && r.Begin > DateTime.Now.AddHours(-24)).ToList();

        if (statusCollection == true) {

            var client = new RestClient("http://1.0.0.111:80/restapi/call");
            var request = new RestRequest(Method.POST);
            request.AddHeader("Postman-Token", "");
            request.AddHeader("cache-control", "no-cache");
            request.AddHeader("Content-Type", "text/xml");
            request.AddParameter("undefined", "@\"\n<event>\n    " +
                "<title>GCP Networking Status</title>\n    " +
                "<description>Google Cloud Platform Newtwork Status</description>\n    " +
                "<application></application>\n    " +
                "<state>Open</state>\n    " +
                "<sub_category></sub_category>\n    " +
                "<hint></hint>\n    " +
                "</related_hints>\n</event>\"@", ParameterType.RequestBody);
            IRestResponse response = client.Execute(request);
        }

        Console.WriteLine(string.Join("\n", statusCollection.Select(s => string.Format("{0} {1} ({2}) {3} - {4} - {5} updates",
                                               s.Begin, s.Number, s.Severity, s.Service_name, s.External_desc, s.Updates.Count))));

        log.Info(DateTime.Now.ToString("MM/dd/yyyy h:mm tt"));
    }
}

1 个答案:

答案 0 :(得分:5)

您正在将列表布尔进行比较。如果要检查集合中是否有任何项目,请使用:

if (statusCollection.Any())

代替:

if (statusCollection == true)