c# object pattern matching for multiple values
I know this is possible:
if (item is { InventoryItemId: 21 })
But I need to do something like this
if (item is { InventoryItemId: [21, 3] })
Is it somehow possible? I dont know how is this called, nor cannot find it after like and hour of googling. I will be glad for any input. Thanks.
No, that's not supported since the value must be a constant since the pattern is evaluated at compile time. So something like this is NOT supported:
int[] values = { 21, 3 };
if(values.Any(v => item is { InventoryItemId: v }))
{
}
So either use something like this (as Ash has commented):
if (item.InventoryItemId is 21 or 3)
{
}
or use another approach to evaluate it (what i would do):
if(values.Contains(item.InventoryItemId)
{
}