I'm trying to make it so I can send queries like: But I am having trouble using the bitwise functions to do so. The var orders is wrong because TypeEnum can't be used with IEnumerable
Asked
Active
Viewed 106 times
1 Answers
1
I think you're doing more work than necessary. Enum.TryParse
is able to take a comma separated list of names and parse it into the correct value:
public static void Get(string orderTypes)
{
var orders = Enumerable.Empty<OrderList>();
if (Enum.TryParse(typeof(TypeEnum), orderTypes, out var enumOrderTypes))
{
orders = _context.OrderLists.Where(o => (o.orderType & enumOrderTypes) > 0);
}
return Ok(orders);
}
However, this assumes that orderTypes
only contains valid enum value names. So if orderTypes
was "Standard,IDontExist"
Enum.TryParse
would return false.
If you want to allow invalid names and just filter them out, you can do it like so:
public static void Get(string orderTypes)
{
var typeList = orderTypes.Split(',',
StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
// I'd recommend adding 'None = 0' as a default value for the enum
TypeEnum enumOrderTypes = TypeEnum.None;
foreach (var strType in typeList)
{
if (Enum.TryParse(typeof(TypeEnum), strType, out var enumType))
{
enumOrderTypes |= (TypeEnum)enumType;
}
}
var orders = _context.OrderLists.Where(o => (o.orderType & enumOrderTypes) > 0);
return Ok(orders);
}
In this example if orderTypes
was "Standard,IDontExist"
, then enumOrderTypes
would end up just containing Standard
.
Check out this fiddle for a demonstration.

Xerillio
- 4,855
- 1
- 17
- 28