danilonet
danilonet

Reputation: 1795

Check if at least one object is not zero

This function need to check that a=b=c=0 or only one is <>0

there is a best way to do this check?

void (int p, int a, int s) {
    if ((p != 0 && a != 0) 
        || (p != 0 && s != 0)
        || (a != 0 && s != 0)
        || (a != 0 && s != 0 && p != 0)) throw new Exception("Error please set A or P or S");

}

Upvotes: 2

Views: 325

Answers (3)

Johnathan Barclay
Johnathan Barclay

Reputation: 20373

void Method(int p, int a, int s)
{
    if (new [] { p, a, s }.Count(i => i == 0) <= 1)
    {
        throw new Exception("Error please set A or P or S");
    }
}

Upvotes: 1

user10216583
user10216583

Reputation:

This function need to check that a=b=c=0 or only one <> 0

If I correctly understand that:

private void CheckValues(int p, int a, int s)
{
    var values = new[] { p, a, s };

    if (values.Sum() == 0 || values.Count(v => v != 0) == 1)
        Console.WriteLine("Error");
    else
        Console.WriteLine("OK");
}

Or

private void CheckValues(params int[] values)
{
    if (values.Sum() == 0 || values.Count(v => v != 0) == 1)
        Console.WriteLine("Error");
    else
        Console.WriteLine("OK");
}

Thus:

CheckValues(0, 0, 0); // <- Error
CheckValues(0, 0, 1); // <- Error
CheckValues(0, 1, 2); // <- OK
CheckValues(1, 2, 3); // <- OK

Upvotes: 1

Peter B
Peter B

Reputation: 24247

A simple solution, without using Linq or any of the overhead that comes with it:

public void Check(int p, int a, int s)
{
    var count = 0;
    if (p != 0) count++;
    if (a != 0) count++;
    if (s != 0) count++;
    if (count >= 2)
        Console.WriteLine("Please set only A or P or S or none");
    else
        Console.WriteLine("OK");
}

Working Fiddle: https://dotnetfiddle.net/ViMmRV

Upvotes: 5

Related Questions