✅ Using Params with Pattern Matching Switch statement
I have the following enums:
I want to link a modification to a query based on which enum you select by switch statement pattern matching:
I can't find a syntax that works with the params keyword. I could do a foreach, but I'm tryign to improve my knowledge.
Is there a way to parse a switch pattern matching using an array of inputs?
12 Replies
I think this would work:
nvm, figured it's betetr to do it like this:
and another function can handle if it's an array
had too many complications. IQueryable needs a generic to search with, so I guess I'll have to make this for each entity that needs to be filtered
here's the final result:
Sounds like you want a flags enum
Enumeration types - C# reference
Learn about C# enumeration types that represent a choice or a combination of choices
They allow you to pass a set of
SearchFilter
values into a single non-array variable of that type.
And you can check for each flag value via switch expression.
It's overlaying bitmasks.That's a great suggestion, but I'm worried about handling conflicting filters (IsArchived true, false, or ignore for example)
Nvm I have that issue anyways
that's actually easy with bit opeartions
it's also a good idea to wrap these in a struct and do helper bool properties
and wrap the bit operations in methods with more intuitive names
flags need a source generator to be great
I probably should write one, I have to deal with this stuff way too often
Do you have an example of what you mean by source generator?
Just use flag enums, no need to overcomplicate it.
True, but I'm trying to overcomplicate ti a bit to learn more. Then I'll know what helps and what's just fluff
Well writing an sg to get flags enum and essentially the same functionality would certainly overcomplicate it. #roslyn has some pinned messages to get you started on that.
yeah learn bit operations first
bit operations is something most people have no knowledge of in my experience
so you could consider it an advanced topic in that sense
No worries on bit operations. I've got a handle on them, just never had a practical use for them until now.
And holy hell, you're not kidding about source generators, I see what you mean now. This is perfect, thanks!
Decided against source generators for now. Not enough benefit for the effort put into it. I want to try it in the future though.
Here's the results: Here are the extensions: just incase someone else could learn from this
Here's the results: Here are the extensions: just incase someone else could learn from this