Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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?

share|improve this question

migrated from stackoverflow.com Mar 21 '14 at 20:28

This question came from our site for professional and enthusiast programmers.

2  
What's wrong with that? Do you need a dynamic list of possible IDs? –  musefan Feb 20 '14 at 16:56
    
No, just wanted to keep it cleaner (looking) .. –  David K Egghead Feb 20 '14 at 16:59
1  
To make it cleaner, I would use an enum or constants instead of the "magic numbers" .. and likely leave the ||s alone for now. –  user2864740 Feb 20 '14 at 17:00
    
In case you've noticed the strange rep losses on your profile, please do not get worried. You haven't done anything wrong. There's a strange bug going on, which is apparently causing your original migrated post from SO to keep duplicating. Hopefully SE can get this fixed soon. –  Jamal Mar 21 '14 at 21:57
    
Should be fixed now. Sorry 'bout that. (cc @Jamal) –  Anna Lear Mar 21 '14 at 22:11

1 Answer 1

up vote 8 down vote accepted

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.

share|improve this answer
    
+1 HashSet is the correct solution. –  Thomas Junk Mar 22 '14 at 7:21

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.