-3

Sometimes i need to use != two, three or four times is there a better way to do it?

if (result != 1 && result != 12)
{
do something 
}


if (result != 1 && != 12)
{
do something 
}

second option would be better, nut we all know it doesn't work

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
  • 5
    The answer is **no** – TheGeneral Jun 07 '19 at 06:59
  • you can try writing an extension method which will take arguments like `result.NotIn(1,12)` – Kaushik Jun 07 '19 at 07:01
  • 1
    Possible duplicate of [if statements matching multiple values](https://stackoverflow.com/questions/3907299/if-statements-matching-multiple-values) and lots of other questions... – Ocaso Protal Jun 07 '19 at 07:01
  • you can add all your values to a list and check with `.Any`. But would probably need a more clear example of what you need – default Jun 07 '19 at 07:01
  • You could do `if (new[] { 1, 12 }.All(x => x != result)) { … }` – ckuri Jun 07 '19 at 07:03
  • Any method call would be even more expesive here. So when the question is really about efficiency, you've got the most efficient way already. Otherwise if it is about the writing tiny and flexible code, there are already some proposals around here. – Christoph Meißner Jun 07 '19 at 07:41

2 Answers2

3

There is not a direct way in the language like the one you suggested:

// Wont compile
if (result != 1 && != 12) { }

If you only have a few values to check, I'd use the explicit comparsions. However you can create a collection of values an check if the result is not in the colleciton:

// using System.Linq;
if (!(new []{ 1, 2 /*, ... */ }).Contains(result)) { }

As suggested in the comments you can also write an extension method. This requires a public static class:

public static class ExtensionMethods
{
    public static bool NotIn(this int num, params int[] numbers)
    {
        return !numbers.Contains(num);
    }
}

// usage

result.NotIn(1, 12);
result.NotIn(1, 12, 3, 5, 6);

And if you want to compare not only integers, you can write a generic method:

public static bool NotIn<T>(this T element, params T[] collection)
{
    return !collection.Contains(element);
}

// Works with different types

result.NotIn(1, 2, 3, 4);   
"a".NotIn("b", "c", "aa");
Emaro
  • 1,397
  • 1
  • 12
  • 21
0

You can use Linq All() method probably

if((new int[]{1,12,13}).All(x => x != result))
{
    // do something
}
Rahul
  • 76,197
  • 13
  • 71
  • 125