I am looking for a way to write something like this:
if (product.Category.PCATID != 10 && produ开发者_运维技巧ct.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 ?
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.
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)) { }
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
}
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) { }
You could do something like that:
List<int> PCATIDCorrectValues = new List<int> {10, 11, 16};
if (!PCATIDCorrectValues.Contains(product.Category.PCATID)) {
// Blah blah
}
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.
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
}
}
精彩评论