473,406 Members | 2,954 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

if Statement with multiple options

3
Hi,

I'm wondering is there a way to shorten this IF statement:

Expand|Select|Wrap|Line Numbers
  1.  if (a == b || a == c || a == d)
  2. {
  3. code
  4. }
  5.  
to
Expand|Select|Wrap|Line Numbers
  1.  if (a == (b or c or d) )
  2. {
  3. code
  4. }
  5.  

Thank you
Oct 19 '10 #1
15 3127
Curtis Rutland
3,256 Expert 2GB
No, there is not.
Oct 19 '10 #2
wyzbs
3
OK. Thanks a lot
Oct 19 '10 #3
GaryTexmo
1,501 Expert 1GB
<digress>
You know, I'm surprised a language hasn't developed something like this. I remember, oh so many years ago, when I first started programming in QBasic I tried to do that exact same thing. My first if statement was something along the lines of...

Expand|Select|Wrap|Line Numbers
  1. IF age = 18 OR 25 THEN
... which is obviously ambiguous, but with the use of brackets the OP's shortened version is clear. Of course, now I'm too used to the current way of doing it, but I do find it noteworthy that new programmers often make that mistake.
</digress>
Oct 19 '10 #4
Curtis Rutland
3,256 Expert 2GB
You know, I've thought about this. You could do something like this, but it's clunky:

Expand|Select|Wrap|Line Numbers
  1. int age = 24;
  2. if ((new int[] { 18, 25 }).Contains(age))
  3.     Console.WriteLine("yes");
  4. else
  5.     Console.WriteLine("no");
Hardly faster than the other way. But if you had four or five values, it might be better.

I've come up with a static class that makes creating these sequences a bit easier:

Expand|Select|Wrap|Line Numbers
  1. public static class Seq
  2. {
  3.     public static IEnumerable<int> Make(int min, int max)
  4.     {
  5.         for (int i = min; i <= max; i++)
  6.             yield return i;
  7.     }
  8.  
  9.     public static IEnumerable<int> Make(Func<int, int> iterator, int min, int max)
  10.     {
  11.         do
  12.         {
  13.             yield return min;
  14.             min = iterator.Invoke(min);
  15.         } while (min <= max);
  16.     }
  17.  
  18.     public static IEnumerable<T> Make<T>(params T[] list)
  19.     {
  20.         foreach (T item in list)
  21.             yield return item;
  22.     }
  23. }
I got the idea from F#'s seq method.

You can easily create a continuous list of ints:
Seq.Make(1, 10)
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
Or one that has an iterator method:
Seq.Make(x => x += 2, 1, 10)
{1, 3, 5, 7, 9}
Or even one with just the values you want:
Seq.Make<int>(1, 2, 4)
{1, 2, 4}
I made that last one generic because it's easy to. The other ones require a numeric type. Generic type constraints are possible, but there is no constraint that says "numeric." So, you could implement the extra methods using doubles/whatever if you wanted to.

I actually like the one that uses a function as a parameter. You can do stuff like this:
Expand|Select|Wrap|Line Numbers
  1. Seq.Make(x => x % 2 == 0 ? x + 3 : x + 5, 1, 50)
1, 6, 9, 14, 17, 22, 25, 30, 33, 38, 41, 46, 49
Or even go so far as to do this:
Expand|Select|Wrap|Line Numbers
  1. private static int DoSomething(int x)
  2. {
  3.     //do lots of stuff to x
  4.     return x + 1;
  5. }
  6. ...
  7. ...
  8. Seq.Make(DoSomething, 1, 10)

Anyway. To your example, you could do something like this:
Expand|Select|Wrap|Line Numbers
  1. if (Seq.Make<int>(18, 25).Contains(age))
  2.     Console.WriteLine("yes");
  3. else
  4.     Console.WriteLine("no");
So, I went off on a tangent of my own, but am having fun.
Oct 19 '10 #5
Curtis Rutland
3,256 Expert 2GB
Oh, I came up with some useful extension methods to go along:

Expand|Select|Wrap|Line Numbers
  1. public static class Extensions
  2. {
  3.     public static bool In(this int i, IEnumerable<int> collection)
  4.     {
  5.         return collection.Contains(i);
  6.     }
  7.  
  8.     public static void Print<T>(this IEnumerable<T> collection, TextWriter writer = null)
  9.     {
  10.         if (writer == null)
  11.             writer = Console.Out;
  12.         StringBuilder sb = new StringBuilder("{");
  13.         foreach (T item in collection)
  14.             sb.Append(string.Format("{0}, ", item));
  15.         sb.Append("}");
  16.         sb.Remove(sb.Length - 3, 2);
  17.         Console.WriteLine(sb.ToString());
  18.     }
  19. }
So, you can do things like:
Expand|Select|Wrap|Line Numbers
  1. if(age.In(Seq.Make(18, 25)))
  2.     Console.WriteLine("yes");
  3. else
  4.     Console.WriteLine("no");
  5.  
Or even 25.In(Seq.Make(18, 25))

Also, the Print method will conveniently print a collection using the provided TextWriter or Console.Out.
Oct 19 '10 #6
GaryTexmo
1,501 Expert 1GB
You know, that's the thing about programmers. We'll happily spend more time avoiding a "problem" than just doing the "workaround" ;)

In the spirit of fun, it occurred to me that you could quite easily create a comparer class to do all sorts of comparisons for you.

Expand|Select|Wrap|Line Numbers
  1.     class Program
  2.     {
  3.         static void Main(string[] args)
  4.         {
  5.             if (Comparer<int>.Compare(Comparer<int>.CompareType.Or, 11, new int[] { 18, 25 }))
  6.             {
  7.                 Console.WriteLine("Pass");
  8.             }
  9.             else
  10.             {
  11.                 Console.WriteLine("Fail");
  12.             }
  13.  
  14.             if (Comparer<string>.Compare(Comparer<string>.CompareType.And, "Gary", new string[] { "Gary", "Gary" }))
  15.             {
  16.                 Console.WriteLine("Pass");
  17.             }
  18.             else
  19.             {
  20.                 Console.WriteLine("Fail");
  21.             }
  22.         }
  23.     }
  24.  
  25.     public static class Comparer<T> where T : IComparable
  26.     {
  27.         public enum CompareType
  28.         {
  29.             Or,
  30.             And
  31.         }
  32.  
  33.         public static bool Compare(CompareType compareType, T value, T[] items)
  34.         {
  35.             bool ret = true;
  36.             foreach (T obj in items)
  37.             {
  38.                 if (value.CompareTo(obj) != 0)
  39.                 {
  40.                     ret = false;
  41.                     if (compareType == CompareType.And) break;
  42.                 }
  43.                 else
  44.                 {
  45.                     ret = true;
  46.                 }
  47.             }
  48.  
  49.             return ret;
  50.         }
  51.     }
I'm willing to bet you could put some LINQ in there as well, but I didn't 'cause I'm not familiar with it. Good ol' foreach for me ;)

If you really wanted to get crazy, you could use a KeyValuePair for your comparisons and include greater than, less than, etc... tests for each value.
Oct 19 '10 #7
GaryTexmo
1,501 Expert 1GB
Hmm also, I can't seem to use your code. Do I need a different version of .NET or VS? I may be out of date... using 2008 and I should have .NET 4.x (w/e it's at) via windows update.
Oct 20 '10 #8
Good job Curtis, for people that do not need the use of Sequences I've derived a simpler extension method from curtis code to allow people to do that kind of stuff:

Expand|Select|Wrap|Line Numbers
  1. if( 1.In(1,2,3,4) )....;
  2. if( 3.123.In(3.1,3.2,3.4) )....;
  3. if( "Hello".In("Hello", "World") )....;
  4.  
  5. if (age.In(18, 25))
  6.     Console.WriteLine("yes");
  7.  else
  8.     Console.WriteLine("no");
etc...

Here it is:

Expand|Select|Wrap|Line Numbers
  1. public static bool In<T>(this T i, params T[] tab)
  2. {
  3.     return tab.Contains(i);
  4. }
Oct 20 '10 #9
Curtis Rutland
3,256 Expert 2GB
I like it, Sigo. You should make an account and start answering questions.
Oct 20 '10 #10
Curtis Rutland
3,256 Expert 2GB
@Gary

I'm using VS2010, but I've tested it in 2008 as well. It requires the following namespaces:

Expand|Select|Wrap|Line Numbers
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
System.Text is for the StringBuilder in the Print extension method.

If that fails, tell me what the exception is.

Also, even though you have .NET 4 from Windows Update, you can't (as far as I'm aware) develop applications for it, because you need to use the .NET 4 SDK, which is not included, and apparently only supports VS2010.
Oct 20 '10 #11
Christian Binder
218 Expert 100+
It's not allowed in 3.5 to use use default-parameters like writer is in
void Print<T>(this IEnumerable<T> collection, TextWriter writer = null)

(btw. what's the tag to make this in-line-code-formatting?)

You could also create a Between-method like 10.Between(9, 11) == 10.In(Seq.Make(9, 11)) == 10.In(Enumerable.Range(9, 3))

Extension methods are really a great thing.
Oct 20 '10 #12
GaryTexmo
1,501 Expert 1GB
I have never heard of extension methods before... and yea I've got it working at work in VS 2010. I may not have the .NET 4 SDK installed at home (O.o) so I'll look into it.

These extension methods... they're freaking cool. They just get picked up out of nowhere? It seems you can name the static class anything and it still attaches the method to the correct type. Quite strange! I'm going to have to do some reading.

Also, best digression thread evar ;)
Oct 20 '10 #13
Curtis Rutland
3,256 Expert 2GB
@Christian
The tag is [icode][/icode].

And I did forget to test the Print method, that's why it was failing. Default/named parameters are a C# 4.0 thing.

And I had forgotten about Enumerable.Range. I knew there was something like it, but I couldn't remember what.
Oct 20 '10 #14
Joseph Martell
198 Expert 128KB
I may be a bit late to the party, but COBOL does allow you to write

Expand|Select|Wrap|Line Numbers
  1. if (a = b or c or d)...
Oct 20 '10 #15
Curtis Rutland
3,256 Expert 2GB
In case anyone still cares about the class and methods we've come up with, I've refined them a bit and posted them to my blog.
Oct 27 '10 #16

Sign in to post your reply or Sign up for a free account.

Similar topics

2
by: Lo La LoooOOOo | last post by:
I also need to movev the data from one to the other.. exemple on image: http://djembefolettes.free.fr/box.gif Thank you very much! -- Lo La LoooOoooOOo Tralala! Na!
1
by: Marie | last post by:
My tables look basically like: TblCustomer CustomerID Customer TblOption OptionID Option TblCustomerOption
5
by: Jai | last post by:
Hi, I am in a problem of sending mass emails(newsletter) to my website members. Actually my problem is this: I want to send newsletter to my website members. But I had given a facility for...
3
tolkienarda
by: tolkienarda | last post by:
hi all i am trying to make a selection box where people can select multiple items then those items will become values assigned to a variable. i am actualy using this in a php/mysql program but i...
3
by: jhh100 | last post by:
Hello.. I have Moderate Knowlege in Access but I'm stumped on how to figure out how to get this done.. I'll try to explain I'm trying to develop a access database that will manage engine...
7
by: magmike | last post by:
I currently have a button once clicked, invokes the following: If Address_Select = -1 Then Forms!ProspectForm!Address = End If However, there are 11 other fields in the subform that i'd like...
1
by: nrsutton | last post by:
Hi I have a real headache of a problem and was wondering if anyone can help me. I'm writing a system that saves stock items. Each item can have none or an infinite number of options attached...
2
by: helplakshmi | last post by:
Hi All, I am new to php. The form that i am designing has few input input fields with submit and reset button. The functionality of submit and reset are working properly till now. My form ...
1
by: love91501 | last post by:
I was wondering if anyone would be able to help me figure out how to make my Q010 have the ability to chose 2 answers, I'm hoping to stay away from checkboxes but I am willing to take in any advice....
0
by: munkee | last post by:
Hi all, I am a bit stumped on this but I think I need to implement a junction table.. which I have never done before. Basically someone reports an event in to my main table, it is assigned an...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.