I have an enum called OrderStatus
, and it contains various statuses that an Order can be in:
- Created
- Pending
- Waiting
- Valid
- Active
- Processed
- Completed
What I want to do is create a LINQ statement that will tell me if the OrderStaus is Valid, Active, Processed or Completed.
Right now I have something like:
var status in Order.Status.WHERE(status =>
status.OrderStatus == OrderStatus.Valid ||
status.OrderStatus == OrderStatus.Active||
status.OrderStatus == OrderStatus.Processed||
status.OrderStatus == OrderStatus.Completed)
That works, but it's very "wordy". Is there a way to convert this to a Contains()
statement and shorten it up a bit?
Assumnig that the enum is defined in the order you specified in the question, you could shorten this by using an integer comparison.
This type of comparison though can be considered flaky. A simply re-ordering of enumeration values would silently break this comparison. I would prefer to stick with the more wordy version and probably clean up it up by refactoring out the comparison to a separate method.
I have used this extension:
You may use this as the condition:
You could put these in a collection, and use:
Sure:
You could also define an extension method
In()
that would accept an object and a params array, and basically wraps the Contains function:This allows you to specify the condition in a more SQL-ish way:
Understand that not all Linq providers like custom extension methods in their lambdas. NHibernate, for instance, won't correctly translate the In() function without additional coding to extend the expression parser, but Contains() works just fine. For Linq 2 Objects, no problems.
If that set of statuses has some meaning, for example those are statuses for accepted orders, you can define an extension method on your enum and use that in your linq query.
Even if you could not give the method a simple name, you could still use something like
IsValidThroughCompleted
. In either case, it seems to convey a little more meaning this way.