4

I am looking for a way to write something like this:

if (product.Category.PCATID != 10 && product.Category.PCATID != 11 && product.Category.PCATID != 16) {   }

In a shorthand way like below, which does not work of course:

if (product.Category.PCATID != 10 | 11 | 16) {   }

So is there shorthand way at all to do something similar ?

LaserBeak
  • 3,257
  • 10
  • 43
  • 73

7 Answers7

6

Yes - you should use a set:

private static readonly HashSet<int> FooCategoryIds
    = new HashSet<int> { 10, 11, 16 };

...

if (!FooCategoryIds.Contains(product.Category.PCATID))
{
}

You can use a list or an array or basically any collection, of course - and for small sets of IDs it won't matter which you use... but I would personally use a HashSet to show that I really am only interested in the "set-ness", not the ordering.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
5

You could use an extension method:

    public static bool In<T>(this T source, params T[] list)
    {
        return list.Contains(source);
    }

And call it like:

  if (!product.Category.PCATID.In(10, 11, 16)) {  }
Hans Kesting
  • 38,117
  • 9
  • 79
  • 111
3

not exactly a shortcut, but maybe the right thing for you.

var list = new List<int> { 10, 11, 16 };
if(!list.Contains(product.Category.PCATID))
{
  // do something
}
yas4891
  • 4,774
  • 3
  • 34
  • 55
2

Well... I think a shorthand version would be if(true), because if PCATID == 10, it is != 11 and != 16, so the whole expression is true.
The same goes for PCATID == 11 and for PCATID == 16.
And for any other number all three conditions are true.
==> You expression will always be true.

The other answers are only valid, if you really meant this:

if (product.Category.PCATID != 10 && 
    product.Category.PCATID != 11 && 
    product.Category.PCATID != 16) {   }
Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
1

You could do something like that:

List<int> PCATIDCorrectValues = new List<int> {10, 11, 16};

if (!PCATIDCorrectValues.Contains(product.Category.PCATID)) {
    // Blah blah
}
Otiel
  • 18,404
  • 16
  • 78
  • 126
1
if (!new int[] { 10, 11, 16 }.Contains(product.Category.PCATID))
{
}

Add using System.Linq to the top of your class or .Contains generates a compile error.

Nope
  • 22,147
  • 7
  • 47
  • 72
0

Make it simple with switch:

switch(product.Category.PCATID) {
    case 10:
    case 11:
    case 16: {
        // Do nothing here
        break;
    }
    default: {
        // Do your stuff here if !=10, !=11, and !=16
        //    free as you like
    }
}
Allen Linatoc
  • 624
  • 7
  • 17