当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - Boolean and/or checking across all elements in an array

问题描述:

I've got two services I'm trying to get the up/down status on. For the first service, only one IP address has to respond to a ping for the service to be considered up. For the second service, all of the IP addresses have to respond to a ping for it to be considered up.

I'm looking for a way to go through the list of IPs and check if one (or all) or the addresses replies to a ping without having to individually call the function on each index in the array. Is there a way to dynamically do this such that adding or removing from the array won't break the way I'm currently doing it?

public static readonly string[] SERVICE1_IPS = {

"address1",

"address2",

"address3"

};

public static readonly string[] SERVICE2_IPS = {

"address1",

"address2",

"address3"

};

static void Main(string[] args)

{

bool status = (PingHost(SERVICE1_IPS[0]) ||

PingHost(SERVICE1_IPS[1]) ||

PingHost(SERVICE1_IPS[2]));

Console.WriteLine("Service 1 status: " + status);

status = (PingHost(SERVICE2_IPS[0]) &&

PingHost(SERVICE2_IPS[1]) &&

PingHost(SERVICE2_IPS[2]));

Console.WriteLine("Service 2 status: " + status);

Console.ReadLine();

}

public static bool PingHost(string hostName)

{

bool pingable = false;

Ping pinger = new Ping();

try

{

PingReply reply = pinger.Send(hostName);

pingable = reply.Status == IPStatus.Success;

}

catch (PingException)

{

}

return pingable;

}

网友答案:

Check out the Enumerable.Any and Enumerable.All extension methods.

static void Main(string[] args)
{
    bool status = SERVICE1_IPS.Any(ip => PingHost(ip));
    Console.WriteLine("Service 1 status: " + status);
    status = SERVICE2_IPS.All(ip => PingHost(ip));
    Console.WriteLine("Service 2 status: " + status);
    Console.ReadLine();
}

Any returns true if and only if the predicate is true for at least one element of the collection.
All returns true if and only if the predicate is true for all elements of the collection.

网友答案:

You could use foreach:

bool status1 = false;
foreach (var ip in SERVICE1_IPS) 
{
    if (PingHost(ip))
    {
        status1 = true;
        break;
    }
}

bool status2 = true;
foreach (var ip in SERVICE2_IPS)
{
    if (!PingHost(ip))
    {
        status2 = false;
        break;
    }
}

Or the System.Linq extension methods Any and All:

var status1 = SERVICE1_IPS.Any(PingHost);
var status2 = SERVICE2_IPS.All(PingHost);
分享给朋友:
您可能感兴趣的文章:
随机阅读: