2
\$\begingroup\$

How can I write this OR statement better, allowing for growth in number of values?

var isNewFile = (progressID == 10 || progressID == 20 || progressID == 21);

I was thinking of this:

var isNewFile = progressID.Contains (10,20,21)

OR using Linq:

.Select or .Contains

Any thoughts?

Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Feb 20, 2014 at 16:55
\$\endgroup\$
3
  • 2
    \$\begingroup\$ What's wrong with that? Do you need a dynamic list of possible IDs? \$\endgroup\$ Commented Feb 20, 2014 at 16:56
  • \$\begingroup\$ No, just wanted to keep it cleaner (looking) .. \$\endgroup\$ Commented Feb 20, 2014 at 16:59
  • 1
    \$\begingroup\$ To make it cleaner, I would use an enum or constants instead of the "magic numbers" .. and likely leave the ||s alone for now. \$\endgroup\$ Commented Feb 20, 2014 at 17:00

1 Answer 1

8
\$\begingroup\$

For something this simple, I think using the || is fine, however, if you need to use the list of acceptable integers more generally or avoid hard-coding the set in a single expression1, you can use something like this:

var newFileProgressIds = new[] { 10, 20, 21 };
var isNewFile = newFileProgressIds.Contains(progressID);

Or possibly use a HashSet<T>:

var newFileProgressIds = new HashSet<int> { 10, 20, 21 };
var isNewFile = newFileProgressIds.Contains(progressID);

1: Of course, in these examples, the values are still hard coded in one place, but precisely how you generate the list is unimportant.

answered Feb 20, 2014 at 16:56
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.